'Save an Image with multer that was created with canvas

I'm currently trying to save an image with multer created with canvas but I can't get it to work my code look like this

const canvas = createCanvas(1000, 1000)
let layout = canvas.getContext('2d')

const image= new Image()

(async () => {
image= await (loadImage(arrayOfImages[randomImage[0]].image_file)) <----- image_file is the file path

}

const img = canvas.toDataURL()
const data = img.replace(/^data:image\/\w+;base64,/, "");

const buf = Buffer.from(data, "base64");

console.log("this is my buf---------------->", buf)

// this is my buf----------------> <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 03 e8 00 00 03 e8 08 06 00 00 00 4d a3 d4 e4 00 00 00 06 62 4b 47 44 00 ff 00 ff 00 ff a0 bd a7 ... 3925 more bytes>
const storage = multer.memoryStorage()
const upload_image = multer({storage: storage});
upload_image.array(buf)

can anyone pls help as I can't find a proper solution to my problem. I check the documentation and I couldn't find anything helpful



Solution 1:[1]

convert your image from DataURL to blob

const dataURItoBlob = function(dataURI : string) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString : string;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}

then upload blob with formdata

const file = dataURItoBlob(canvas.toDataURL())
const form = new FormData()
form.append('file',file)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phạm Vỹ