3

我有一个#mycanvas包含图像的画布。我想从该图像中创建一个 blob,最好是 jpeg。这是我创建blob的方式

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

我如何从这个 blob 重新创建图像,并#mycanvas再次显示它?

4

3 回答 3

4

这是我解决问题的方法

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

调用时收到 blobcanvas.toDataURL("image/jpeg")

于 2013-08-24T14:19:50.933 回答
2

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

function blob2canvas(canvas,blob){
    var img = new window.Image();
    img.addEventListener("load", function () {
        canvas.getContext("2d").drawImage(img, 0, 0);
    });
    img.setAttribute("src", blob);
}
于 2017-01-24T18:33:54.437 回答
0

从 Blob 样本恢复到画布,取自: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);
}
于 2020-09-24T15:04:40.370 回答