[英]nodejs convert image between buffer and string
我想將 png 圖像從buffer
轉換為string
,然后將字符串轉換為緩沖區。
fs.readFile('/Users/xxx/Desktop/1.png', (err, data) => {
if (err) throw err; // Fail if the file can't be read.
data = Buffer.from(data)
let str = data.toString()
data = Buffer.from(str)
});
// server
router.register('/api/dump', (request, response) => {
fs.readFile('/Users/xxx/Desktop/1.png', (err, data) => {
if (err) throw err; // Fail if the file can't be read.
response.writeHead(200, {'Content-Type': 'image/jpeg'});
response.end(data); // Send the file data to the browser.
});
})
// front
this.$get('/dump').then(result => {
// i want to convert result to buffer
})
但新緩沖區不再是舊緩沖區。
Buffer.toString()
默認編碼是utf8
,你不能在不破壞圖像的情況下從utf8
轉換回Buffer
。
如果要轉換為字符串,然后再轉換回緩沖區,則需要使用允許這樣做的編碼,例如base64
。
fs.readFile('/Users/yihchu/Desktop/1.png', (err, data) => {
if (err) throw err; // Fail if the file can't be read.
var oldData = data;
let str = data.toString('base64')
data = Buffer.from(str, 'base64');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.