ImageAsset ( image ) To base64 in Cocos Creator 3.0

Hello Everyone ,
i want to share with you my solution of getting base64 url of a image using Cocos Creator 3.0.
this is based on @FinlayAceViral solution

start(){
    //make sure your image is in resources directory/sub-dir 
    //load the asset as ImageAsset 
    // Once the loading process finishes use the function below to get base64 image
    resources.load("examples/test",ImageAsset,(err: Error | null, image: ImageAsset)=>{
            const base64Image : string = this.ImageToDataURL(image);
            console.info(base64Image);
    })
}


public ImageToDataURL( image: ImageAsset) : string {
        const canvas = document.createElement("canvas"); // Create a canvas
        const context = canvas.getContext("2d"); // get the context
        canvas.width = 600; // canvas width
        canvas.height = 200; //canvas height
        context?.drawImage(<CanvasImageSource> image.data, 0, 0,  image.width,  image.height); //draw image using image.data
        return canvas.toDataURL();
    }

Happy coding :wink:

3 Likes

Thanks for sharing!

1 Like

Do you have a solution for converting RenderTexture to base64 data? Thank you.

i don’t think i have any idea for this at the moment :smiley: , i hope i can help later on !