NodeJS stream image from web, convert to WebP

2k Views Asked by At

I need to stream images from the web (using a dummy image here) which are in jpg format and then convert them to WebP. This is a one at a time conversation (not bulk)

I have the following code which pulls an image and saves it as a .jpg successfully.

const axios = require("axios")
const fs = require("fs")
const imagemin = require("imagemin")
const imageminWebp = require("imagemin-webp")


async function axios_get_contents (uri, callback) {
    await axios({
        "method": "get",
        "url": uri,
        "responseType": "stream"
    }).
        then((response) => {
            console.log("then1")
            response.data.pipe(fs.createWriteStream("pic1.jpg"))
        })
}

const URL = "https://images.pexels.com/photos/1449767/pexels-photo-1449767.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"


axios_get_contents(URL).then((ret) => console.log(ret))

Below is where I'm stuck. I'm trying to convert to webp. Essentially the imagemin code is running before the jpg is created.

async function axios_get_contents (uri, callback) {
    await axios({
        "method": "get",
        "url": uri,
        "responseType": "stream"
    }).
        then((response) => {
            console.log("then1")
            response.data.pipe(fs.createWriteStream("pic1.jpg"))
        }).
        then((response) => {
            console.log("then2")
            imagemin(["pic1.jpg"], {
                "destination": "compressed-images",
                "plugins": [imageminWebp({"quality": 50})]
            })
        })
}

Questions:

How can I successfully chain on the webp conversion?

Do I need to write a jpg file and then read the same file back into imagemin? Can I just pass a buffer/var to imagemin? Would saving reading and writing.

thanks heaps!!

1

There are 1 best solutions below

0
Adam On

Either of these worked for me

// Stream
async function axios_get_contents6 (url, callback) {
    const imageResponse = await axios({"method": "get",
        url,
        "responseType": "stream"})
    await imageResponse.data.pipe(sharp().webp({"quality": 50}).
        toFile("output6.webp", (err, info) => {
            console.log(`err: ${err}`)
    }))
}

// Buffer
async function axios_get_contents7 (url, callback) {
    const imageResponse = await axios({"method": "get",
        url,
        "responseType": "arraybuffer"})
    const buffer = Buffer.from(imageResponse.data, "binary")
    await sharp(buffer).
        webp({"quality": 50}).
        toFile("output5.webp", (err, info) => {
            console.log(err)
    })
}