Native Base64 to Image

Native Base64 to Image
0

#1

Saw a lot of posts about converting base64 string to image. Most of them are for web only or requires manual binding. Is there any method to do this on native platform without manual binding?


#2

It seems cocos does not support any class or component to do this officially.

try the code below, it works in my project:

            const buffer = new Buffer(this._data, 'base64');
            const len = buffer.length;
            const bytes = new Uint8Array(len);
            for (let i = 0; i < len; i++) {
                bytes[i] = buffer[i];
            }

            const extName = this.format === DataFormat.PNG ? 'png' : 'jpeg';
            const randomFileName = `base64_img_${new Date().getTime()}.${extName}`;
            const dir = `${jsb.fileUtils.getWritablePath()}${randomFileName}`;

            if (jsb.fileUtils.writeDataToFile(bytes, dir)) {
                cc.loader.load(dir, (err, texture) => {
                    if (!err && texture) {
                        this.target.spriteFrame = new cc.SpriteFrame(texture);
                        cc.loader.release(dir);
                    }
                    jsb.fileUtils.removeFile(dir);
                });
            }

#3

Holy shit you saved my life!