Native Base64 to Image

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?

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);
                });
            }
4 Likes

Holy shit you saved my life!

Saved mine too! :smiley: :+1: