Actor picture

Example Image Download

lukaskrivka/download-image

Download a single image from a URL and store it into a key-value store.

No credit card required

Author's avatarLukáš Křivka
  • Modified
  • Users46
  • Runs282,015
Actor picture

Example Image Download

Based on the apify/actor-node-basic:v0.21.10 Docker image (see docs).

const Apify = require('apify');
const rp = require('request-promise');

Apify.main(async () => {
    // Get input of your actor
    const input = await Apify.getInput();
    console.log('My input:');
    console.dir(input);

    const {
        imageUrl,
        proxy = { useApifyProxy: false },
        // Optional headers
        headers = {},
    } = input;

    // Optional proxy
    const proxyConfiguration = await Apify.createProxyConfiguration(proxy);

    // encoding: null means that we download raw binary data 
    // which is what we want for an image
    const imageBuffer = await rp({
        url: imageUrl,
        encoding: null,
        proxy: proxyConfiguration ? proxyConfiguration.newUrl() : null,
        headers,
        gzip: true,
    });
    console.log(`Image downloaded`)
    await Apify.setValue('OUTPUT', imageBuffer, { contentType: 'image/png' });
    
    console.log('Image is saved at:');
    const storeId = Apify.getEnv().defaultKeyValueStoreId;
    console.log(`https://api.apify.com/v2/key-value-stores/${storeId}/records/OUTPUT?disableRedirect=true`);
});