HTML5画布,保存jpeg blob并从blob恢复到画布

时间:2013-08-24 13:46:07

标签: javascript html5 html5-canvas

我有一张包含图片的画布#mycanvas。我想用该图像创建一个blob,最好是作为jpeg。这是我如何创建blob

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

如何从此blob重新创建图像,并再次在#mycanvas中显示?

3 个答案:

答案 0 :(得分:3)

以下是我解决问题的方法

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

调用canvas.toDataURL("image/jpeg")

时收到blob

答案 1 :(得分:1)

安东的回答不再有效。你现在需要这个语法。

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

答案 2 :(得分:0)

从“ https://googlechrome.github.io/samples/image-capture/grab-frame-take-photo.html

”获取的Blob示例恢复到“画布”
// 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);
}