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!!
Either of these worked for me