Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Data URI to File

Tags:

javascript

I want to convert a data:image encoded with base64 to a normal image file. So far my code looks like this:

this.toDataURL = function() {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    canvas.width = innerWidth;
    canvas.height = innerHeight;
    ctx.drawImage(layer0, 0, 0);
    ctx.drawImage(layer1, 0, 0);
    ctx.drawImage(layer2, 0, 0);
    var url = canvas.toDataURL('image/png');
    document.getElementById('canvascontent').value = url;
};

As you can see it creates an DataUrl that is afterwards displayed in an output(#cancascontent). The final output looks something like this:

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

My problem is that I need it necessarily decoded so that I can upload the images. My aim is that my javascript code displays the image in a new window like a "normal" image file. For example. like this:

http://example.com/images/pro_js_3e.png

How can I decode the base64 image?

like image 374
Em Sta Avatar asked Jun 26 '13 19:06

Em Sta


People also ask

How do I convert a URL to an image?

Free tool to convert Data URI to image (png) file. Data URI is an Uniform Resource Identifier scheme that provides a way to include data in-line in webpages. You need to copy & paste the Data URI as input and you can save the output image file. Note : For reverse conversion, use Image to DataURI Converter.

How do you use data URI?

A data URI is a base64 encoded string that represents a file. Getting the contents of a file as a string means that you can directly embed the data within your HTML or CSS code. When the browser encounters a data URI in your code, it's able to decode the data and construct the original file.


1 Answers

You can convert the canvas to a Blob, and then upload that.

To convert to a Blob, try this script: https://github.com/blueimp/JavaScript-Canvas-to-Blob

Then you can use canvas.toBlob instead of canvas.toDataURL.

Then to upload it, you need to use FormData

canvas.toBlob(function(blob){
    var form = new FormData(),
        request = new XMLHttpRequest();

    form.append("image", blob, "filename.png");
    request.open("POST", "/upload", true);
    request.send(form);
}, "image/png");

This is un-tested, but should work.

like image 111
Rocket Hazmat Avatar answered Oct 02 '22 14:10

Rocket Hazmat