Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a base64 to a file in Javascript

The goal is to transform a base64 string into a sendable jpg file, I cant use the html input type file but i have to serve in the same format. I am bit lost with file generation. (I am on a client side mobile app).

This is what i have:

 file = "data:image/jpg;base64,#{imageData}"

imageData is the base64 string

There is a way to transform this into a valid file?

like image 370
Imnl Avatar asked Mar 23 '14 10:03

Imnl


People also ask

How do I get files from Base64?

How to convert Base64 to file. Paste your string in the “Base64” field. Press the “Decode Base64 to File” button. Click on the filename link to download the file.

How can I convert Base64 image to typescript?

Just create an image, set the src to the data URL, and use that image for your <image-cropper>. In any event, check my answer, should set you in the right direction if you absolutely most convert the data URL to something useful, such as a blob.

Can we convert Base64 to JSON?

Decode your Base64 data into JSON format. Input (Base64) - Paste your Base64 here. Upload Download Copy to Clipboard Conversion is Automatic. Output (JSON) - The converted JSON.

Is Base64 a blob?

2 Answers. base64 encoding: A binary-to-text encoding scheme whereby an arbitrary sequence of bytes is converted to a sequence of printable ASCII characters, as described in RFC4648. binary large object (BLOB): A discrete packet of data that is stored in a database and is treated as a sequence of uninterpreted bytes.

How to decode Base64 strings in JavaScript?

In JavaScript, there are two functions for decoding and encoding base64 strings: btoa()which is used to create a base-64 encoded ASCII string from a string of binary data and atob(), which decodes a base64 encoded string.

What is Blob and how to convert Base64 into blob in JavaScript?

What is Blob and how to convert base64 into blob in javascript? lobs are immutable objects that represent the raw data. the file in javascript is a derivation of Blob that describe the data from file system. You can construct the file like objects, you can construct a Blob containing the data for an image.

How do I upload a Base64 file to a server?

First, pass a base64 string to fetch: Depending on the format of the base64 string, you might need to prepend content type data. For example, a JPEG image: Next, convert the response to a blob: That’s it! From here, you can upload it to a server, display it on the screen, and more.

What is Base64 Base64?

Base64 is a collection of binary-to-text encoding schemes representing binary data during an ASCII string format by translating it into a radix-64 representation. Base64 is an encoding algorithm allowing to convert any characters into an alphabet, which consists of Latin letters, digits, plus, and slash.


Video Answer


1 Answers

Disclaimer: Produces an invalid result (close, but invalid)

I've done the reverse earlier last week - that is, load an image as binary data (to get around the requirement to run file from localhost).

In it, I:

  • loaded the file
  • base64 converted it
  • added a pre-amble to the base64 string
  • set the constructed string to be the src of an img element

This worked just fine. Upon reading your question, I tried to simply reverse the process. I was however, unsuccessfull somewhere. The data is extracted from the image correctly, then somewhere afterwards (I think in the call to atob that un-encodes it) the data is messed-up.

The saved files are an unexpected size, have an added char before "%PNG" and have some missing data in the middle of the file. I'm rather perplexed at this point, to be honest.

Anyhow, here's the code I've tried:

1. Code to read a file and stuff the data into an element

// fileVar is an object as returned by <input type='file'>
// imgElem is an <img> element - (doesn't need to be added to the DOM)
function loadImgFromFile(fileVar, imgElem)
{
    var fileReader = new FileReader();
    fileReader.onload = onFileLoaded;
    fileReader.readAsBinaryString(fileVar);
    function onFileLoaded(fileLoadedEvent)
    {
        var result,data;
        data = fileLoadedEvent.target.result;
        result = "data:";
        result += fileVar.type;
        result += ";base64,";
        result += btoa(data);
        imgElem.src = result;
    }
}

2. Attempt to grab data from an image/canvas and force the download of it using a programmer-supplied filename.

<!doctype html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e)}
function newEl(tag){return document.createElement(tag)}
window.addEventListener('load', onPageLoaded, false);

function onPageLoaded(evt)
{
    var imgElem = byId('srcImg');
    imgElem.onload = function(){saveImgAsFile( byId('srcImg'), "myImage.png" );};

        // simple result of canvas.toDataURL() called on a 5x5 pixel image of a '+'
    imgElem.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHklEQVQIW2NkQID/QCYjiAsmoABFEMRBAThVYmgHAAhoBQWHhfyYAAAAAElFTkSuQmCC"; 

    // use the below line instead of the one above, if you wish to assign an actual image file, rather than the result of call to canvas.toDataURL()
    // the base64 string allows me to keep it all in the one file, also, to run if opened via a double-click, rather than having to run from localhost
//  imgElem.src = "img/1x1.png";
}

function saveImgAsFile(imgElem, fileName)
{
    // get a base64 encoded string from an image element
    var srcElem = imgElem;
    var dstCanvas = newEl('canvas');
    dstCanvas.width = srcElem.naturalWidth;
    dstCanvas.height = srcElem.naturalHeight;
    var ctx = dstCanvas.getContext('2d');
    ctx.drawImage(srcElem,0,0);
    var imgSrcStr = dstCanvas.toDataURL();

    // extract the image type
    var colonPos = imgSrcStr.indexOf(":");
    var semiColonPos = imgSrcStr.indexOf(";");
    var imgType = imgSrcStr.slice(colonPos+1, semiColonPos);
    console.log("image type: " + imgType);

    // extract the image data
    var commaPos = imgSrcStr.indexOf(',');
    var base64ImgString = imgSrcStr.slice(commaPos + 1);
    console.log("Data: " + base64ImgString);

    // holds the data that is actually written to disk for this image
    //** I think the error occurs during this step **//
    var unencodedImage = atob(base64ImgString);

    var imgFileAsBlob = new Blob( [unencodedImage], {type: imgType} );
    var fileNameToUse = fileName;

    var downloadLink = newEl('a');
    downloadLink.download = fileNameToUse;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null)
    {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(imgFileAsBlob);
    }
    else
    {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(imgFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }
    downloadLink.click();
}

/*

function saveTextAsFile()
{
    var textToWrite = "This is just some random content";
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'})
    var fileNameToSaveAs = "myFile.txt";

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null)
    {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    }
    else
    {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }
    downloadLink.click();
}
*/
function destroyClickedElement(event)
{
    document.body.removeChild(event.target);
}
</script>
</head>
<body>
    <img id='srcImg'/>
</body>
</html>
like image 82
enhzflep Avatar answered Oct 30 '22 19:10

enhzflep