how to convert png image string data in to png? - javascript

Look at my code
<img src='data:image/png;base64,{{imgSrc}}'>
In my controller
$scope.imgSrc = $scope.deviceDetail.imgSrc;
I am getting this type of response from my backend in imgSrc which is stored in mongodb.
"�PNG\r\n\u001a\n\u0000\u0000\u0000\rIHDR\u0000\u0000\u0003 \u0000\u0000\u0002R\b\u0002\u0000\u0000\u0000��6A\u0000\u0000\u0000\u0006bKGD\u0000�\u0000�\u0000�����\u0000\u0000 \u0000IDATx���{xT���W x\u0000\u0006%$F�c F\t�\"�V��\u0000�P\u000f\b���xEъ��T�z#� \u0018�諀`�TJ�Z\u0015\t�\"R��#\u000b|H�h8\u0005\......"
Now I want png image from this data,I have tried this data into base64 but still not getting image.
Please suggest me what is wrong here?

You can convert image to data base64 bit.
Base64 is a group of similar binary-to-text encoding schemes that represent
binary data in an ASCII string format by translating it into a radix-64 representation.
To convert a file to base64 (image or any other kind of file) with cordova, ionic or phonegap we will need only the cordova file plugin and 1 human eye. Then we will use the FileReader to read the the content of a file with the method readAsDataURL.
/**
* This function will handle the conversion from a file to base64 format
*
* #path string
* #callback function receives as first parameter the content of the image
*/
function getFileContentAsBase64(path,callback){
window.resolveLocalFileSystemURL(path, gotFile, fail);
function fail(e) {
alert('Cannot found requested file');
}
function gotFile(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var content = this.result;
callback(content);
};
// The most important point, use the readAsDatURL Method from the file plugin
reader.readAsDataURL(file);
});
}}
Then we will use it to convert a local image to base64 :
var path = "file://storage/0/downloads/myimage.png";
// Convert image
getFileContentAsBase64(path,function(base64Image){
//window.open(base64Image);
console.log(base64Image);
// Then you'll be able to handle the myimage.png file as base64
});
Remember that you need the file plugin from cordova, read and learn how to use it here. You can download the file plugin into your project executing in your cordova CLI :
cordova plugin add cordova-plugin-file
continue here
https://gist.github.com/HereChen/e173c64090bea2e2fa51
http://tutsheap.com/web/javascript/get-base64-image-url/

Related

How to convert a PDF file into a base64 string in java script

I have created an app in sencha touch cordova, and in my app I have a functionality to download PDFs.
I have successfully downloaded a pdf file, but now I want to convert the PDF into a base64 string using JavaScript.
Can anybody tell me how to do it?
See if your JavaScript environment has the "atob" and "btoa" functions available:
var encodedData = window.btoa("Hello, world"); // encode a string
var decodedData = window.atob(encodedData); // decode the string
These convert a string to and from Base64 encoding.
Trying using the logic below.
<input id="inputFile" type="file" onchange="convertToBase64();" />
function convertToBase64(){
//Read File
var selectedFile = document.getElementById("inputFile").files;
//Check File is not Empty
if (selectedFile.length > 0) {
// Select the very first file from list
var fileToLoad = selectedFile[0];
// FileReader function for read the file.
var fileReader = new FileReader();
var base64;
// Onload of file read the file content
fileReader.onload = function(fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
// Print data in console
console.log(base64);
};
// Convert data to base64
fileReader.readAsDataURL(fileToLoad);
}
}
Note : This snippet was taken from stackoverflow, but I dont remember the link :(

Calculate MD5 or SHA of an Image using CryptoJS

I have a requirement where I need to calculate hash of an Image and upload it to a webservice. The image is captured using Cordova API and the API returns a URI of that image.
I checked the CryptoJS but it is taking a string as input.
var hash = CryptoJS.MD5("Message");
Any way we can calculate hash for the image ?
CryptoJS Lib : CryptoJS Home Page
Any other library is also fine as long as it can be used from Cordova App.
Using Cordova API you can get a Base64 encoded image instead of the URI. Which you can easily hash using CryptoJS.
When calling getPicture API use the DATA_URL option to get Base64 encoded image as the result:
navigator.camera.getPicture(onSuccess, onFail, {
destinationType: Camera.DestinationType.DATA_URL });
This will return the base64 encoded image in the onSuccess method as the param:
function onSuccess(imageURI) {
var hash = CryptoJS.MD5(imageURI);
}
Here is my way to generate the MD5 of the image file in HTML:
function onFileChange (e) {
const readerBuffer = new FileReader()
readerBuffer.readAsBinaryString(e.target.files[0])
readerBuffer.onloadend = function (e) {
const hash = CryptoJS.MD5(CryptoJS.enc.Latin1.parse(e.target.result))
const content-md5 = hash.toString(CryptoJS.enc.Base64)
}
}
Need to read the image as binary.
After reading this, I got that we need to convert the string to bytes using Latin-1.
This result can be used as content-md5 by AWS required.

How to convert a captured media file into base64 using javascript?

I am developing an application using phone gap. I capture image/audio/video and store its path in local storage. I need to fetch base64 of captured file and store it in the database and then sync it with server. Is that possible using javascript ?
I tried using FileReader API that phone gap provides but the function reader.onloadend() does not get executed.
Could manage to get base64 of image using a canvas but is it possible to get base64 for audio and video using canvas?
Thanks.
Yes It's possible to get the base64 of a media file
reader.onloadend() is not being called because you might have missed this line reader.readAsDataURL(file).
// here i have a file input and i am using the FileReader Api to read the content on it's change event ( i have no idea what is the event for capturing a media in phonegap
$("#file").change(function(e){
var file = e.currentTarget.files[0];
var FR = new FileReader();
FR.onload = function (encodedFile) {
//alert("onload is called.");
}
FR.onloadend = function (encodedFile) {
var src = encodedFile.target.result;
src = src.split("base64,");
// This is the base64 encoded string of that media file which you will be interested to store in the database(post to the server
var contentAsBase64EncodedString = src[1];
}
reader.readAsDataURL(file);
}

Convert image from readAsDataURL to readAsBinaryString

Using the filereader API it is possible to show a preview of the file, by reading the file with readAsDataURL
What I am trying to do is:
The user selects a file
A preview is shown, so that the user has some feedback.
If the user is satisfied, he submits the data to the backend.
Implementing step 3 can be done by re-reading the file with readAsBinaryString, but this looks problematic because the data could have disappeared or changed on disk. So What I would like is to convert the data returned from readAsDataURL to the format returned by readAsBinaryString. How can I do this?
Another alternative would be to submit the data to the backend as returned by readAsDataURL, but I would like to avoid that, since that would require special handling on the backend in my case.
Like CBroe said, you dont need to read the file twice.
JS :
handleFileSelectThumbFile(evt){
var files = evt.target.files;
var file = files[0];
// You can get the mime type like this.
var thumbMIME = files[0]['name'].split('.').pop();
if (files && file) {
var reader = new FileReader();
reader.onload = function(readerEvt) {
// Split the readerEvt.target.result by a ','.
// You can send the binaryString variable to the server.
// Its base64 encoded already.
var binaryString = readerEvt.target.result.split(',')[1];
// Set the image preview to the uploaded image.
$('.img-preview').prop('src', readerEvt.target.result);
}.bind(this);
reader.readAsDataURL(file);
}
}
HTML :
<input type="file" onChange={this.handleFileSelectThumbFile} required/>
<img src='http://placehold.it/300' class='img-preview'/>
You can read the MIME type from the first part of readerEvt as well. Look at CBroe's comment above.

Decode base64 image and upload

I have a webapp that is saving images locally until they are ready to be sent to the server. When I save the images locally, I base64 encode them. Now I want to do a multipart file upload with these images.
So I need to convert the image back into binary form. I've tried using the FileReader to convert it back like this,
var fr = new FileReader();
fr.onloadend = function(binaryImage){
debugger;
binaryImage;
};
var base64Str = item.base64Image.substr(item.base64Image.indexOf("base64") + 7);
//var base64Str = item.base64Image;
fr.readAsBinaryString(base64Str);
but the onloadend event is never fired and there are no errors. Once I get the image I wont have trouble uploading it. Any ideas?
Thanks!
Not to familiar with FileReader, but I believe readAsBinaryString is expecting a Blob or File object. Passing it a string causes errors on my end. Try this:
var fr = new FileReader();
fr.onloadend = function(binaryImage){
debugger;
binaryImage;
};
var blob = new Blob([item.base64Image.
substr(item.base64Image.indexOf("base64") + 7)]);
fr.readAsBinaryString(blob);
I don't think this will give you want though. Check out this article for ways to encode/decode Base64: How can you encode to Base64 using Javascript?
Looks like you can use btoa() and atob() for web kit browsers.

Categories