Anton Gildebrand
Anton Gildebrand

Reputation: 3707

HTML5 canvas, save jpeg blob and restore to canvas from blob

I have a canvas #mycanvas which contains an image. I want to create a blob out of that image, preferably as a jpeg. Here is how i create the blob

document.getElementById('mycanvas').toDataURL("image/jpeg").replace(/^data:image\/(png|jpeg);base64,/, "")

How do i recreate the image from this blob, and show it in #mycanvas again?

Upvotes: 3

Views: 14665

Answers (3)

patrick
patrick

Reputation: 16959

Restore to Canvas from Blob sample taken from: https://googlechrome.github.io/samples/image-capture/grab-frame-take-photo.html

// ms is a MediaStreamPointer
let imageCapture = new ImageCapture(ms.getVideoTracks()[0]);

                imageCapture.takePhoto()
                    .then(blob => createImageBitmap(blob))
                    .then(imageBitmap => {
                        const canvas = document.getElementById('canvas')
                        drawCanvas(canvas, imageBitmap);
                    })

function drawCanvas(canvas, img) {
    canvas.width = getComputedStyle(canvas).width.split('px')[0];
    canvas.height = getComputedStyle(canvas).height.split('px')[0];
    let ratio = Math.min(canvas.width / img.width, canvas.height / img.height);
    let x = (canvas.width - img.width * ratio) / 2;
    let y = (canvas.height - img.height * ratio) / 2;
    canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
    canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height,
        x, y, img.width * ratio, img.height * ratio);
}

Upvotes: 1

Leonardo Max Almeida
Leonardo Max Almeida

Reputation: 46

Anton's answer no longer works as it is. You need this syntax now.

function blob2canvas(canvas,blob){
    var img = new window.Image();
    img.addEventListener("load", function () {
        canvas.getContext("2d").drawImage(img, 0, 0);
    });
    img.setAttribute("src", blob);
}

Upvotes: 2

Anton Gildebrand
Anton Gildebrand

Reputation: 3707

Here's how i solved my problem

function blob2canvas(canvas,blob){
    var img = new Img;
    var ctx = canvas.getContext('2d');
    img.onload = function () {
        ctx.drawImage(img,0,0);
    }
    img.src = blob;
}

The blob was received when calling canvas.toDataURL("image/jpeg")

Upvotes: 4

Related Questions