How to generate an Image from imageData in javascript?

后端 未结 4 718
日久生厌
日久生厌 2020-12-25 10:45

I would like to know if there is any way to create a new Image from imageData, which was previously obtained from a canvas element?

I\'ve searched for a solution, bu

相关标签:
4条回答
  • 2020-12-25 11:09

    A lot of modern browsers support Data URI scheme.

    If you have the image data, you can set the src attribute of an img element using JavaScript.

    Look at the following example: http://www.websiteoptimization.com/speed/tweak/inline-images/

    0 讨论(0)
  • 2020-12-25 11:17

    You can use toDataURL method in Canvas. It makes a image data as Data URI.

    var canvas = document.createElement("canvas");
    canvas.width = 100;
    canvas.height = 100;
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "red";
    ctx.fillRect(0, 0, 100, 100);
    
    var img = document.createElement("img");
    img.src = canvas.toDataURL("image/png");
    document.body.appendChild(img);
    

    If you want to know user's browser supports Data URI Scheme, You can use this function.

    function useSafeDataURI(success, fail) {
        var img = document.createElement("img");
    
        img.onerror = function () {
            fail();
        };
        img.onload = function () {
            success();
        };
    
        img.src = "data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; // insert a dot image contains 1px.
    }
    
    0 讨论(0)
  • 2020-12-25 11:24

    Assuming this is your canvas

    <canvas id='mycanvas'></canvas>
    

    You can get a representation of your image using

    var imgData = document.getElementById('mycanvas').toDataURL();
    

    You could then put that in a regular image tag by changing its source

    <img id='myimage'/>
    
    document.getElementById('myimage').src = imgData;
    
    0 讨论(0)
  • 2020-12-25 11:31

    None of the previous answers provide an answer to the question as it was presented in the subject - getting an Image from ImageData. So here's a solution.

    function imagedata_to_image(imagedata) {
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        canvas.width = imagedata.width;
        canvas.height = imagedata.height;
        ctx.putImageData(imagedata, 0, 0);
    
        var image = new Image();
        image.src = canvas.toDataURL();
        return image;
    }
    
    0 讨论(0)
提交回复
热议问题