save IMG from external site

Asked

Viewed 1,320 times

0

Is there a possibility to save an image in a folder /imagens from an external website?

I can save normal image if I right click and put in "Save image as", but I would like to know how to do this in Javascript or PHP, I inspected and the element is this:

<img id="imagem" alt="Painel" src="http://appsite/caminho/caminho2/Content/caminho3/Painelimg/2018_03_02/08_03_28.PNG" style="width: 2790.72px; height: 391.68px;">

NOTE: This image is generated every 10 seconds, so I need to save it automatically only the name of the image is the current time, for example, this time I inspected the image name is 08_03_28.png ie was 08h:03m:28s I don’t need to save all I can override them too, I just need the image in that moment because I will do another function.

3 answers

1

You can also do with the NodeJs.

You can use the http to download the image and the pipe to write the image on your system.

let output = fs.createWriteStream(file);

http.get(URL, response => {
    response.pipe(output);
});

Code:

const URL = "http://appsite/caminho/caminho2/Content/caminho3/Painelimg";
const http = require("http");
const fs = require("fs");

async function startDownload() {

    const date = new Date();

    /* Captura a data */
    let year = date.getFullYear();
    let month = (date.getMonth()+1).toString().padStart(2, "0");
    let day = date.getDay().toString().padStart(2, "0");

    /* Captura o tempo */
    let hour = date.getHours().toString().padStart(2, "0");
    let min = date.getMinutes().toString().padStart(2, "0");
    let seconds = date.getSeconds().toString().padStart(2, "0");

    let datePath = `${year}_${month}_${day}`
    let file = `${hour}_${min}_${seconds}.PNG`

    /* Baixa a imagem */
    http.get(`${URL}/${datePath}/${file}`, async (response) => {
        await wait(10000);
        startDownload();
    });

};

function wait(ms) {
    return new Promise( resolve => setTimeout(resolve, ms) )
}

startDownload();

1


There are two ways to do this with PHP.

Example with file_get_contents:

This function will access the page and download all its content, to save, we can use fopen or file_put_contents.

<?php

while (true) {

    /* Captura a data atual */
    $date = date('Y_m_d');

    /* Captura o tempo patual */
    $time = date('H_i_s');

    /* Monta a URL com a data e o tempo */
    $url = "http://appsite/caminho/caminho2/Content/caminho3/Painelimg/{$date}/{$time}.PNG";

    /* Faz uma requisição para a URL e salva o conteúdo em binário na variável */
    $content = file_get_contents($url, FILE_BINARY);

    /* Cria o arquivo no servidor com o conteúdo baixado */
    file_put_contents( "{$time}.png", $content, FILE_BINARY );

    /* Aguarda 10 segundos */
    sleep(10);
}

Ready! It’s working. The problem is while(true) will be infinite and therefore you may have a problem with the server resources.

If it’s something sporadic, no problem.


Example with curl:

This function will also make a request and return the data, but will have a few more lines. The advantage is that it is more robust than the previous function.

To save, we can use fopen or file_put_contents.

<?php

while (true) {

    /* Captura a data atual */
    $date = date('Y_m_d');

    /* Captura o tempo patual */
    $time = date('H_i_s');

    /* Monta a URL com a data e o tempo */
    $url = "http://appsite/caminho/caminho2/Content/caminho3/Painelimg/{$date}/{$time}.PNG";

    /* Cria o arquivo. Caso ele já exista, sobrepõe */
    $file = fopen("{$time}.png", "w+");

    /* Instancia o objeto */
    $ch = curl_init($url);

    /* Define as configurações */
    curl_setopt_array($ch, [

        /* Informa que deseja capturar o valor retornado */
        CURLOPT_RETURNTRANSFER => true,

        /* Indica o "Resource" do arquivo onde será salvado */
        CURLOPT_FILE           => $file
    ]);

    /* Fecha a conexão da requisição e do arquivo */
    curl_close($ch);
    fclose($file);

    /* Aguarda 10 segundos */
    sleep(10);
}
  • I realized that the image by the way I indicated it is all black but on the site it is black but with a few letters, I think it is done in canvas, when I saved by the mouse everything comes right however by the code or the link I posted straight from the image comes all black, will q there is another way?

  • @Ixxtomxxl if possible put the image link, it is easier to test. It is necessary to check the extension as well. Have you tested with both forms or just one of them?

  • so the link only works within the company, I tried to get only the div that contains the image with file_gets_contents worked on other sites, but not on that. If you have another way I would like to present you with something, if possible within the rules of the site.

0

you can also use the function copy() php

bool copy ( string $source , string $dest [, resource $context ] )

basically will use the first 2 parameters

source: Path to source file.

dest: The destination path. If dest is a URL, the copy may fail if the wrapper does not support overwriting of existing files.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.