直接用texture2d 的updatedata方法得到结果是噪点。感觉少了某个环节。imageasset又是如何实现的,通过AI根本找不到答案,给的是猜测推理代码,不是参数不对就是方法不存在。有没有技术大牛知道如何实现。
先转成base64,然后就能转过来了
try {
const filePath="/storage/emulated/0/Download/19060eb31020b9b0a1fc76e4ffe52df5.png"
// 1. 检查文件是否存在
if (!native.fileUtils.isFileExist(filePath)) {
throw new Error("文件不存在: " + filePath);
}
// 2. 读取文件数据
const data = native.fileUtils.getDataFromFile(filePath);
if (!data || data.byteLength === 0) {
throw new Error("读取的文件数据为空");
}
const width = 256; // 图像宽度
const height = 256; // 图像高度
texture = new Texture2D();
texture.reset({
width,
height,
format: Texture2D.PixelFormat.RGBA8888, // 根据实际格式调整
});
// 将 ArrayBuffer 写入纹理(需确保数据格式匹配)
//const u8 = new Uint8Array(data);
const base64 = btoa(String.fromCharCode(...new Uint8Array(data))); // 性能较差
texture.uploadData(base64);
// 5. 验证纹理是否有效
if (texture.width === 0 || texture.height === 0) {
throw new Error("纹理创建失败=,可能图片格式不支持");
}
} catch (error) {
throw error;
}
#你说的上面这样吗?uploadData不能传base64
api有保存的方法,找不到读取的方法。
native.saveImageData(new Uint8Array(data),256,256,filePath)
用UPNG.js 转成base64 再转spriteframe
private toBase64(){
const bytesPerRow = width * 4;
const u8 = new Uint8Array(data);
for (let y = 0; y < height; y++) {
const srcStart = (height - 1 - y) * bytesPerRow;
const dstStart = y * bytesPerRow;
u8.set(data.slice(srcStart, srcStart + bytesPerRow), dstStart);
}
const pngData = UPNG.encode([u8.buffer], width, height, 0, 0);
const base64 = “data:image/png;base64,” + this.arrayBufferToBase64(pngData);
}
private arrayBufferToBase64(buffer: ArrayBuffer): string {
let binary = ‘’;
const bytes = new Uint8Array(buffer);
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}