stc*_*t12 8 base64 buffer node.js sharp
我正在尝试对节点中的图像进行下采样.我将该图像存储为base64编码的字符串(即:"data:image/png; base64,iVBOR"等).我正在使用Sharp npm包.该文档似乎描述了锐利可以将文件路径带到图像或"inputBuffer".我做了一些谷歌搜索并假设Buffer类是他们所指的.连续尝试下面的代码导致我收到以下错误:"输入缓冲区包含不受支持的图像格式." 我的问题可能是什么,如果你不确定,请你推荐一个不同的npm包,文件更清晰?
const downsizeProfileImgForTweet = (user, cb) => {
let imgBuffer = Buffer.from(user.profileImg, 'base64');
sharp(imgBuffer)
.resize(52, 52)
.toBuffer()
.then(data => {
console.log("success");
user.profileImg = data;
cb()
} )
.catch( err => console.log(`downisze issue ${err}`) );
}
Run Code Online (Sandbox Code Playgroud)
我浏览了整个互联网并做了一堆猜测和检查,所以请原谅我的noob问题.提前感谢您提供的任何帮助!
您需要删除“data:image/png;base64”部分。
所以你在这里:
const uri = user.profileImg.split(';base64,').pop()
const downsizeProfileImgForTweet = (user, cb) => {
let imgBuffer = Buffer.from(uri, 'base64');
sharp(imgBuffer)
.resize(52, 52)
.toBuffer()
.then(data => {
console.log('success')
user.profileImg = data
cb()
})
.catch(err => console.log(`downisze issue ${err}`))
}
Run Code Online (Sandbox Code Playgroud)
不确定它是否适用于 ".toBuffer() 方法,尽管它对我来说是这样的(写入文件):
sharp(imgBuffer)
.resize(1920, null)
.toFile(`${config.images_path}/${picture.filename}`)
.then(data => {
console.log('normal: ', data)
})
.catch(err => console.log(`downisze issue ${err}`))
Run Code Online (Sandbox Code Playgroud)
不久前我还在为此苦苦挣扎……
尝试这个?
const buf = new Buffer(img.replace(/^data:image/\w+;base64,/, ""),'base64')
| 归档时间: |
|
| 查看次数: |
1830 次 |
| 最近记录: |