Save Canvas image with Deno

Viewed 336

I have in the client side a JS script which gets some Canvas, converts it to a DataURL, and send it through some FormData.

     let image = canvas.toDataURL("image/png");
     let formData = new FormData();
     formData.append('Canvas_Image', image);

How can I save it in Deno (using Oak) as a file image?

1 Answers

The issue is now solved, so here are the results.

First, as the method toDataURL converted the canvas image into a Base64 string, I have used the standard library of Deno for the encoding/decoding methods:

    import { decode as base64Decode, encode as base64Encode } from 'https://deno.land/std@0.82.0/encoding/base64.ts';

    // Read the FormData in Oak server:
    const body = await request.body({ type: 'form-data'});
    const form = await body.value.read();

     // Get the Image from the FormData (wich comes encoded in a base64 string)
     let Image = form.fields.Canvas_Image;
    
     // Replace characters so the decoding has no problems.
     Image = Image.replace("data:image/png;base64,", "");
     Image = Image.replace(" ", "+");
    
     // Use this method from the std library to decode it:
     let DecodedImage = base64Decode(Image);
    
     // Save the decoded image using Deno.writeFile()
     let URI_Image = "./path/to/save/your/image.png";
     await Deno.writeFile(URI_Image, DecodedImage);

And that's all, it should save your image in the server correctly.

Related