NodeJS从web流图像,转换为WebP



我需要从网络流式传输jpg格式的图像(此处使用伪图像(,然后将它们转换为WebP。这是一次一个的对话(不是批量(

我有下面的代码,它成功地提取了一个图像并将其保存为.jpg。

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))

下面是我被卡住的地方。我正在尝试转换为webp。从本质上讲,imagemin代码是在创建jpg之前运行的。

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})]
})
})
}

问题:

我如何才能成功地进行webp转换?

我需要写一个jpg文件,然后把同一个文件读回imagemin吗?我可以将buffer/var传递给imagemin吗?会节省阅读和写作。

非常感谢!!

这两种方法都适用于我的

// 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)
})
}

最新更新