【问题标题】:HTML5 canvas, save jpeg blob and restore to canvas from blobHTML5 画布,保存 jpeg blob 并从 blob 恢复到画布
【发布时间】:2013-08-24 13:46:06
【问题描述】:

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

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

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

【问题讨论】:

标签: javascript html html5-canvas


【解决方案1】:

这是我解决问题的方法

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

【讨论】:

  • 我该如何反其道而行之?从画布中获取 blob?
  • @EnriMR document.getElementById('mycanvas').toDataURL("image/jpeg")
  • @AntonGildebrand,将画布转换为正确的Blob toBlob() 方法不是正确的方法吗?
  • 这不再准确,您必须从 blob img.src = URL.createObjectURL(blob); 创建一个 url
【解决方案2】:

Anton 的回答不再适用。你现在需要这个语法。

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

【讨论】:

    【解决方案3】:

    从 Blob 样本恢复到 Canvas,取自: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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-13
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 2012-07-26
      相关资源
      最近更新 更多