JS: how can I base64 encode a local file without XMLHttpRequest? - javascript

I'm trying to base64 encode a local file. It's next to my .js file so there's no uploading going on. Solutions like this (using XMLHttpRequest) get a cross-site scripting error.
I'm trying something like this (which doesn't work but it might help explain my problem):
var file = 'file.jpg'
var reader = new FileReader();
reader.onload = function(e) {
var res = e.target.result;
console.log(res);
};
var f = reader.readAsDataURL(file);
Anyone have any experience doing this locally?

Solutions like this (using XMLHttpRequest) get a cross-site
scripting error.
If using chrome or chromium browser, you could launch with --allow-file-access-from-files flag set to allow request of resource from local filesystem using XMLHttpRequest() or canvas.toDataURL().
You can use <img> element, <canvas> element .toDataURL() to create data URL of local image file without using XMLHttpRequest()
var file = "file.jpg";
var img = new Image;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
img.onload = function() {
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
ctx.drawImage(this, 0, 0);
var res = canvas.toDataURL("image/jpeg", 1); // set image `type` to `image/jpeg`
console.log(res);
}
img.src = file;
You could alternatively use XMLHttpRequest() as described at Convert local image to base64 string in Javascript.
See also How to print all the txt files inside a folder using java script .
For a details of difference of returned data URI from either approach see canvas2d toDataURL() different output on different browser
As described by #Kaiido at comment below
it will first decode it, at this stage it's still your file, then it
will paint it to the canvas (now it's just raw pixels) and finally it
will reencode it (it has nothing to do with your original file
anymore) check the dataURI strings... They're compeltely different and
even if you do the canvas operation from two different browsers,
you'll have different outputs, while FileReader will always give you
the same output, since it encode the file directly, it doesn't decode
it.

Related

Store animated GIF image in local Storage using pure JavaScript

I have a requirement where I need to store the GIF image in local storage. I have been trying to do this using following code:
function imgToURI(image) {
var canvasTemp = document.createElement('canvas');
canvasTemp.width = image.naturalWidth; // or 'width' if you want a special/scaled size
canvasTemp.height = image.naturalHeight; // or 'height' if you want a special/scaled size
canvasTemp.getContext('2d').drawImage(image, 0, 0);
var dataUri = canvasTemp.toDataURL('image/gif');
// Modify Data URI beginning
dataUri = 'data:image/gif;' + dataUri.substring(15);
return dataUri;
}
window.onload = function () {
var img = new Image();
img.src = 'http://pop.h-cdn.co/assets/16/33/480x264/gallery-1471381857-gif-season-2.gif';
localStorage.setItem('test', imgToURI(img));
};
The above code outputs data:image/gif; in local storage. Also I can't find any errors on console.
I have been trying a lot but don't know why image is not getting stored. Please let me know if you have solution to above problem.
maybe when your code is executed the image was not loaded yet. So only the string 'data:image/gif will be saved
var img = new Image();
img.addEventListener('load', function() {
localStorage.setItem('test', imgToURI(img));
}, false);
img.src = 'http://pop.h-cdn.co/assets/16/33/480x264/gallery-1471381857-gif-season-2.gif';
this code will attempt to save the image only if its loaded completely
EDIT
You are having this error because the image the image is not coming from your server: this CORS issue. you can try this but you have to trust the server who host the image
just before the addEventListener
img.setAttribute('crossOrigin', 'anonymous');
It can be due to Cross-Origin request not allowing you to get the canvas data. You have to make sure to use an image from a "trusted" source (server which allows Cross-Origin on your domain), so that your canvas doesn't get tainted.

canvas2d toDataURL() different output on different browser

I have the same image and the same size of canvas, but the output is different. I want the same output, how should I do it?
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL();
setBreakpoint(dataURL);
callback.call(this, dataURL);
canvas = null;
};
img.src = url;
Images drawn onto a canvas are decoded before being drawn, then reencoded when the toDataURL method is called.
This process will produce some variations in every browser (e.g some will be able to decode color-profiles embedded in the image while others won't), and even every machine (look at canvas fingerprinting and this post by #Oriol which concern images with transparency). Add to that that every browser will use different encoders/settings for a different tradeoff between speed, size and quality and you arrive at a situation where you can't expect two users to produce the same result from the same input image.
But since all you do with that canvas is to draw an image, you should rather use a FileReader and its method readAsDataURL(). For external files, you can still use it by first fetching the resource as a Blob.
This will work directly on the binary data of the file, encoding each byte to its base64 representation, and thus you will be sure to have the same result in every browser.
Here is a snippet which will test your browser's conversion against mine's.
fetch("https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png")
.then((resp) => resp.ok && resp.blob())
.then((blob) => {
const reader = new FileReader();
reader.onload = (evt) => {
if (reader.result === imageDataURL) {
console.log("same result");
}
else {
console.log("please post a comment stating which browser has such a bug");
}
};
reader.readAsDataURL(blob);
});
var imageDataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAAEzo7pQAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC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vsHeYQPOG4I7Y4BgAPJ58uLepJHbasMwEAXHkhJVMgkNtv//A2XRtL7JEK/y0LqmrqEPfVuWw7B75teCv/rhQCQQqjHV0GZYjf4MNG1RtjVy0Sz9EYGaQEJr0CS6DaLLryGWrtemP+XO5+m63P0uEL3GTOaUkyN5hfmYinz325GMSDOmwtoZXMR7RqrvGwLqQhduvJ1Jn42B2xUV5boMGAvzozkqSm56UOrVDYMtw1Ggee9KJ0Wh1Isl7F1EkGpkUiA4Zs7yELXaiwCy4WRlr19U/7L5HAAZyaffhXaAFwAAAABJRU5ErkJggg=="
However for the ones using the canvas for real drawing, as we said above, you can't really have the same results between different UAs. Every method from drawing ones to export ones may produce different results and you would have to actually rewrite all these methods entirely in order to have the exact same results.
For the ones that really need this, a project like node-canvas could help, though it would obviously be a lot less performant than native implementations.

How to encrypt and decrypt image files online?

I'm working on a web application that involves loading images into a canvas object, then manipulating those images beyond recognition. I need to hide the original source image file (a jpeg) so that the user on the client side should not be able to use dev tools to see the original image.
I have tried to encode the images as a base64 and load it via a JSON data file, but even with this method, the inspector tool still shows the original image file (when it is set as the src of my javascript image object). Is there some way that I can encrypt and decrypt the image files, so that the user has no way of seeing the original image (or have it be some garbled image, for example)? Preferably I'd like to do this on the client side, as all my code is client side at the moment. Thanks in advance!
Here is my code for loading the base64 encoded image data via a JSON file:
//LOAD JSON INSTEAD?
$.getJSON( "media/masks.json", function( data ) {
console.log("media/masks.json LOADED");
//loop through data
var cnt = 0;
for (var key in data)
{
if (data.hasOwnProperty(key))
{
// here you have access to
//var id = key;
var imgData = data[key];
//create image object from data
var image = new Image();
image.src = imgData;
console.log('img src: '+ imgData);
var elementId = $scope.masks[cnt].id;
// copy the images to canvases
imagecanvas = document.createElement('CANVAS');
imagecanvas.width = image.width;
imagecanvas.height = image.height;
imagecanvas.getContext('2d').drawImage(image,0,0);
imageCanvases[elementId] = imagecanvas;
}
cnt++;
}
});
This is what I see in the Chrome dev tools Network inspector (exactly what I'm trying to avoid):
I need to hide the original source image file (a jpeg) so that the user on the client side should not be able to use dev tools to see the original image.
That's not possible. There is always a way to get at the image using developer tools. Even if there wasn't, a simple screen capture would defeat whatever measures you put in place.

converting canvas to blob using cropper js

I have created an application using cropper.js for cropping an images. The application is working and the image is cropping, after that I am trying to send the cropped image as blob to the server side for storing,
As per the cropper.js documentation we can use canvas.toDataURL to get a Data URL, or use canvas.toBlob to get a blob and upload it to server with FormData. when I tried canvas.toDataURL() I am getting the base64 string, but actually I need to send the file as blob so I tried with canvas.toBlob() but I am getting Uncaught TypeError: canvas.toBlob is not a function in chrome and TypeError: Not enough arguments to HTMLCanvasElement.toBlob. in Firefox
Can anyone please tell me some solution for this
My code is like this
var canvas = $image.cropper("getCroppedCanvas", undefined);
var formData = new FormData();
formData.append('mainImage', $("#inputImage")[0].files[0]);
formData.append('croppedImage', canvas.toBlob());
The method toBlob is asynchronous and require two arguments, the callback function and image type (there is optional third parameter for quality):
void canvas.toBlob(callback, type, encoderOptions);
Example
if (typeof canvas.toBlob !== "undefined") {
canvas.toBlob(function(blob) {
// send the blob to server etc.
...
}, "image/jpeg", 0.75);
}
else if (typeof canvas.msToBlob !== "undefined") {
var blob = canvas.msToBlob()
// send blob
}
else {
// manually convert Data-URI to Blob (if no polyfill)
}
Not all browsers supports it (IE needs prefix, msToBlob, and it works differently than the standard) and Chrome needs a polyfill.
Update (to OP's edit, now removed) The main reason why the cropped image is larger is because the original is JPEG, the new is PNG. You can change this by using toDataURL:
var uri = canvas.toDataURL("image/jpeg", 0.7); // last=quality
before passing it to the manual data-uri to Blob. I would recommend using the polyfill as if the browser supports toBlob() it will be many times faster and use less memory overhead than going by encoding a data-uri.
The proper use: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob
you have to pass the callback and use the blob object within callback. toBlob() does not returns the blob rather it accepts a callback which provides blob as parameter.
var canvas = document.getElementById("canvas");
canvas.toBlob(function(blob) {
var newImg = document.createElement("img"),
url = URL.createObjectURL(blob);
newImg.onload = function() {
// no longer need to read the blob so it's revoked
URL.revokeObjectURL(url);
};
newImg.src = url;
document.body.appendChild(newImg);
});

How do I save and restore a File object in local storage

I have an HTML5/javscript app which uses
<input type="file" accept="image/*;capture=camera" onchange="gotPhoto(this)">
to capture a camera image. Because my app wants to be runnable offline, how do I save the File (https://developer.mozilla.org/en-US/docs/Web/API/File) object in local storage, such that it can be retrieved later for an ajax upload?
I'm grabbing the file object from the using ...
function gotPhoto(element) {
var file = element.files[0];
//I want to save 'file' to local storage here :-(
}
I can Stringify the object and save it, but when I restore it, it is no longer recognised as a File object, and thus can't be used to grab the file content.
I have a feeling it can't be done, but am open to suggestions.
FWIW My workaround is to read the file contents at store time and save the full contents to local storage. This works, but quickly consumes local storage since each file is a 1MB plus photograph.
You cannot serialize file API object.
Not that it helps with the specific problem, but ...
Although I haven't used this, if you look at the article it seems that there are ways (although not supported yet by most browsers) to store the offline image data to some files so as to restore them afterward when the user is online (and not to use localStorage)
Convert it to base64 and then save it.
function gotPhoto(element) {
var file = element.files[0];
var reader = new FileReader()
reader.onload = function(base64) {
localStorage["file"] = base64;
}
reader.readAsDataURL(file);
}
// Saved to localstorage
function getPhoto() {
var base64 = localStorage["file"];
var base64Parts = base64.split(",");
var fileFormat = base64Parts[0].split(";")[1];
var fileContent = base64Parts[1];
var file = new File([fileContent], "file name here", {type: fileFormat});
return file;
}
// Retreived file object
Here is a workaround that I got working with the code below. I'm aware with your edit you talked about localStorage but I wanted to share how I actually implemented that workaround. I like to put the functions on body so that even if the class is added afterwards via AJAX the "change" command will still trigger the event.
See my example here: http://jsfiddle.net/x11joex11/9g8NN/
If you run the JSFiddle example twice you will see it remembers the image.
My approach does use jQuery. This approach also demonstrates the image is actually there to prove it worked.
HTML:
<input class="classhere" type="file" name="logo" id="logo" />
<div class="imagearea"></div>
JS:
$(document).ready(function(){
//You might want to do if check to see if localstorage set for theImage here
var img = new Image();
img.src = localStorage.theImage;
$('.imagearea').html(img);
$("body").on("change",".classhere",function(){
//Equivalent of getElementById
var fileInput = $(this)[0];//returns a HTML DOM object by putting the [0] since it's really an associative array.
var file = fileInput.files[0]; //there is only '1' file since they are not multiple type.
var reader = new FileReader();
reader.onload = function(e) {
// Create a new image.
var img = new Image();
img.src = reader.result;
localStorage.theImage = reader.result; //stores the image to localStorage
$(".imagearea").html(img);
}
reader.readAsDataURL(file);//attempts to read the file in question.
});
});
This approach uses the HTML5 File System API's to read the image and put it into a new javascript img object. The key here is readAsDataURL. If you use chrome inspector you will notice the images are stored in base64 encoding.
The reader is Asynchronous, this is why it uses the callback function onload. So make sure any important code that requires the image is inside the onLoad or else you may get unexpected results.
You could use this lib:
https://github.com/carlo/jquery-base64
then do something similar to this:
//Set file
var baseFile = $.base64.encode(fileObject);
window.localStorage.setItem("file",basefile);
//get file
var outFile = window.localStorage.getItem("file");
an other solution would be using json (I prefer this method)
using: http://code.google.com/p/jquery-json/
//Set file
window.localStorage.setItem("file",$.toJSON(fileobject));
//get file
var outFile = $.evalJSON(window.localStorage.getItem("file"));
I don't think that there is a direct way to Stringify and then deserialize the string object into the object of your interest. But as a work around you can store the image paths in your local storage and load the images by retrieving the URL for the images. Advantages would be, you will never run out of storage space and you can store 1000 times more files there.. Saving an image or any other file as a string in local storage is never a wise decision..
create an object on the global scope
exp: var attmap = new Object();
after you are done with file selection, put your files in attmap variable as below,
attmap[file.name] = attachmentBody;
JSON.stringify(attmap)
Then you can send it to controller via input hidden or etc. and use it after deserializing.
(Map<String, String>)JSON.deserialize(attachments, Map<String,String>.class);
You can create your files with those values in a for loop or etc.
EncodingUtil.base64Decode(CurrentMapValue);
FYI:This solution will also cover multiple file selection
You could do something like this:
// fileObj = new File(); from file input
const buffer = Buffer.from(await new Response(fileObj).arrayBuffer());
const dataUrl = `data:${fileObj.type};base64,${buffer.toString("base64")}`;
localStorage.setItem('dataUrl', dataUrl);
then you can do:
document.getElementById('image').src = localStorage.getItem('dataUrl');

Categories