gpt4 book ai didi

javascript - 将整数数组解码为 PNG(JavaScript、node.js)

转载 作者:行者123 更新时间:2023-11-29 22:45:44 26 4
gpt4 key购买 nike

我正在尝试将整数数组转换为 PNG 文件。

function saveImg(data, dir, name, waveBand) {
if (!fs.existsSync(dir)){
logger.info(dir + ' does not exist... creating!');
fs.mkdirSync(dir);
}

logger.info('received data with length ' + data.length);
try {
const encoder = new util.TextDecoder("utf-8");
const decodedData = encoder.decode(new Uint8Array(data));
logger.info('decoded string: ' + decodedData);
const imgLocation = path.join(getStoragePublicFolder(), dir, name + '.png');
logger.info('Writing image to location: ' + imgLocation);

fs.writeFile(path.resolve(imgLocation), decodedData,
function(err) {
if(err)
logger.info(err);
}
);

logger.info('Success! Image saved to ' + imgLocation);
return imgLocation;
}
catch (err)
{
logger.error('Failed to save image - ' + err);
}
return defaultPath(waveBand);
}

我的数据如下所示:https://jsfiddle.net/ebaxg3q4/

不幸的是,数据解码出现问题,因此 image is corrupted .

这是哪种编码?我犯了什么错误?

提前致谢!

最佳答案

您可以使用 Buffer.from(Array) 从站点位图数据创建缓冲区。

然后我们可以使用 fs.writeFile 将缓冲区写入 .png 文件。

此代码适用于我(使用您的示例数据):

function saveImg(data, dir, name, waveBand) {
if (!fs.existsSync(dir)){
logger.info(dir + ' does not exist... creating!');
fs.mkdirSync(dir);
}

logger.info('received data with length ' + data.length);
try {
const decodedData = Buffer.from(data);
const imgLocation = path.join(getStoragePublicFolder(), dir, name + '.png');
logger.info('Writing image to location: ' + imgLocation);
fs.writeFile(path.resolve(imgLocation), decodedData,
function(err) {if(err) logger.info(err);});
logger.info('Success! Image saved to ' + imgLocation);
return imgLocation;
} catch (err){ logger.error('Failed to save image - ' + err); }
return defaultPath(waveBand);
}

// Use the first station in the station list.
saveImg(dummyStation.stationList[0].stationIconPicture.data.data, "./test", "station");

关于javascript - 将整数数组解码为 PNG(JavaScript、node.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58728065/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com