简体   繁体   中英

Html5 Canvas and base64 image

I have a base64 image which looks like this:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUAAAADwCA...... 

is there a way i can draw this on a canvas using the above encoded image? Does anyone have an example of this.

Edited:

This is working for me and its drawing the image only when its an image and not base64

This works:

<script type="text/javascript">

        var pos = 0, ctx = null, ctx2 = null,saveCB, image = [], image2 = new Image();

        var canvas = document.createElement('canvas');


        var image2 = new Image();

        canvas.setAttribute('width', 320);
        canvas.setAttribute('height', 240);
        ctx = canvas.getContext('2d');
        image = ctx.getImageData(0, 0, 320, 240);

        var saveCB = function (data) {
            var col = data.split(';');
            var img = image;
            for (var i = 0; i < 320; i++) {
                var tmp = parseInt(col[i]);
                img.data[pos + 0] = (tmp >> 16) & 0xff;
                img.data[pos + 1] = (tmp >> 8) & 0xff;
                img.data[pos + 2] = tmp & 0xff;
                img.data[pos + 3] = 0xff;
                pos += 4;
            }

            if (pos >= 4 * 320 * 240) {
                ctx.putImageData(img, 0, 0);
                foto = canvas.toDataURL("image/png");
                $("#photo").val(foto);
                alert($("#photo").val()); 


                ctx2 = document.getElementById("canvas2").getContext("2d");
                ctx2.clearRect(0, 0, 320, 240);
                image2.src = 'http://blackberry12.com/uploads/allimg/110311/2-110311153Z90-L.jpg';
                ctx2.drawImage(image2,0,0);           

                pos = 0;
            }
        };
</script>

if i change image2.src to foto or $("#photo").val() i am not getting anything just a white canvas.

Edited From my investigation i am getting the same base64 code every time i take a pic and encode. It seems like the base64 code is really a white screen. Can anyone help here, cant see where i made the error.

Absolutely.

var img = new Image();
img.src = "data:image/png;base64,.............";
ctx.drawImage(img,0,0);

The image is immediately available for drawing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM