假设一张图片60*60,那么就是3600个像素,每一个像素点RGBA描述需要4个数字,也就是描述这一张图片需要3400*4=13600。数组长度要达到13600才可以正常描述这个图片。
以下是js转换RGBA数据到base64格式的demo(适用于Web)
<!DOCTYPE html><html><body><img id="myimage"></img><script>function rgbaTobase64(array,width,height){let arr = new Uint8ClampedArray(width*height*4);for(let i=0;i<width*height*4;i++){arr[i]=myarray[i];}// Initialize a new ImageData objectlet imageData = new ImageData(arr, width,height);const c1 = document.createElement("canvas");var ctx1=c1.getContext("2d");ctx1.putImageData(imageData,0,0);let dataURL = c1.toDataURL("image/png");return dataURL;}let myarray=[73,73,73,255,...太长,省略];let width=60;let height=60;let base64=rgbaTobase64(myarray,60,60);document.getElementById('myimage').src=base64;</script></body></html>
以下是cocos专用RGBA数据转spriteFrame(适用于cocos编译的web平台和windows平台,其他平台未测试。)
public static rgbaToSpriteFrame(rgbastr){let myarray=rgbastr.split(",");let width=64;let height=64;let arr = new Uint8ClampedArray(width*height*4);for(let i=0;i<width*height*4;i++){arr[i]=myarray[i]-0;}var texture = new cc.RenderTexture();texture.initWithData(arr,32,width, height);//texture.update({minFilter:cc.Texture2D.Filter.NEAREST,magFilter:cc.Texture2D.Filter.NEAREST,format:cc.Texture2D.PixelFormat.RGBA32F});var newframe = new cc.SpriteFrame(texture);return newframe;}