Javascript: How to save file location to local storage? - javascript

In Javascript (w/ Angular 2+) I have an app where I am trying to save a dataURl to localstorage once it has been picked by a user. Currently I have tried the following code but on retrieval I get an empty obj {} as the body.
HTML
<input style="display:none;" type="file" (change)="fileEvent($event)" #file>
Angular File Storage and Retrieval Function
fileEvent(ev: any): void {
console.log('Event select file', ev);
let obj: any = ev.target.files[0];
let file: File = {
Key: obj.name,
ContentType: obj.type,
Size: obj.size,
Body: obj
};
localStorage.setItem("myapp", JSON.stringify(file);
}
getFileFromLocalStorage {
console.log(JSON.parse(localStorage.getItem("myapp"));
}
File Retrieval Response below

You can not store image directly to localstorage like this. First you need to convert the image to Base64. Then save the Base64 string in localStorage value.
Below is function to convert Image into Base64:
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
Now you can save this to your local storage.
Here is the reference answer on SO.

Related

How to encode an <input type="file> as a base64 string?

I am trying to send an image to my express backend. I have tried adding the image directly to my post request body.
var imgValue = document.getElementById("image").value;
In my post request
body : JSON.stringify({
image:imgValue
})
Accessing the image on the backend only gives me the name of the file. Is there any way I can encode the image as a base64 string in the frontend itself?
You need to load the image into a temporary img element and then you can convert it to base64 when the temporary element has loaded the image.
Use the image as img.src = (YourImageSource)
From the onload function you can then retrieve the base64 value.
var imgEl = document.createElement('img');
imgEl.onload = function(){
var canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this,0,0);
const d = canvas.toDataURL('image/jpeg');
console.log('base64',d);
};
imgEl.src = img;
Run below code, if you already upload your file then the console will show the base64 of the file
The example is for only first file.
If you need upload more than one files. You can loop to make it.
document.getElementById("image").files;
Using files array to get each file's base64.
var file = document.getElementById("image").files[0];
var reader = new FileReader();
reader.onload = function (r) {
var fileInfo = new Object();
fileInfo.name = file.name;
fileInfo.size = file.size;
fileInfo.extension = file.name.split(".")[file.name.split(".").length - 1];
console.log(r.target.result.split("base64,")[1]);
};
reader.onerror = function (ex) {
console.error(ex);
};
reader.readAsDataURL(file);

Save the blob url image from using viewer.screenshot() to server/database

I used forge viewer api. Viewer.screenshot() to get the image of a component. It returns a blob url as the image. E.g “blob:localhost:3000/afdijhejsbjdjd”. But I need to save this image to my local server, how can I achieve this? Using Nodejs.
How can I change this blob url to a transferable image url?
We can convert the image Blob URL to a based64 encoded string like the below, and then
function getScreenShotImageBase64(viewer, width, height) {
return new Promise((resolve) => {
viewer.getScreenShot(width, height, blobURL => {
let img = new Image();
let tmpCanvas = document.createElement('canvas');
let ctx = tmpCanvas.getContext('2d');
tmpCanvas.width = width;
tmpCanvas.height = height;
img.onload = function() {
// draw viewer image on canvas
ctx.drawImage(img, 0, 0, width, height);
resolve(tmpCanvas.toDataURL('image/png'));
};
img.src = blobURL;
});
});
}
let imageBase64 = await getScreenShotImageBase64(viewer, viewer.container.offsetWidth, viewer.container.offsetHeight);
Here is the preview of the result:
Afterward, send the base64 string to your backend server, and then you can either save the image base64 string to your database,
Or resave the base64 string to file. For example in nodejs.
fs.writeFileSync(path.join(uploadPath, fileName), new Buffer(base64, 'base64'))
ref: How to upload image using Base64 string in NodeJs

Convert Link from Image URL from s3 into File Object using JavaScript

I want to convert my s3 image link into a file object using JavaScript.
I've found out how to do this with an image URI but wasn't able to figure out how to convert the image URL into a URI. Once I do this I could convert it into a file object
Heres the image link:
http://s3.us-east-2.amazonaws.com/rentpop/298%2F2014-mclaren-650s-Spyder-Tarocco-Orange-2.jpg
Source for this code
function getDataUri(url, callback) {
var image = new Image();
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
// Get raw image data
callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''));
// ... or get as Data URI
callback(canvas.toDataURL('image/png'));
};
image.src = url;
}
// Usage
getDataUri('local_location_to_image.extension', function(dataUri) {
// Do whatever you'd like with the Data URI!
});

Convert image extracted from URL to base64

I am fetching the user's Facebook profile picture whenever they login via Facebook. I want to convert the image to base 64 from the URL. What would be the best way of doing this, while ensuring that the user can still see their profile picture in the view (home.view)? At the moment, I am directly referring to the URL.
This is my code so far:
facebook.service.js
function FacebookService($http, config) {
this.getUserPicture = function(userId, token) {
return $http({
method: 'GET',
url: 'https://graph.facebook.com/' + userId + '/picture?type=large&redirect=false'
})
}
}
home.controller.js
function HomeController($scope, $cordovaNativeStorage, FacebookService, $ionicLoading) {
if (window.cordova) {
// Get Facebook access token
$cordovaNativeStorage.getItem("facebookAccessToken").then(function(value) {
$scope.facebookAccessToken = value
// Get Facebook user picture (currently stored as a URL, would want to store it as a base 64 string which can be displayed as an image
FacebookService.getUserPicture($scope.facebookUserData.id).then(function(dataResponse) {
$scope.facebookUserPicture = dataResponse.data;
// Save Facebook user picture
$cordovaNativeStorage.setItem("facebookUserPicture", $scope.facebookUserPicture).then(function() {}, function(error) {
console.error("Unable to cache user data: " + result);
$ionicLoading.show({
template: 'Unable to cache user data',
duration: 1500
})
});
}, function(error) {
console.log(error.data.error.message)
})
}, function(error) {
console.log(error.data.error.message)
})
}
};
home.view.js
<img class="icon icon-home img-circle" ng-src="{{ facebookUserPicture.data.url }}">
There's a method to do it via canvas (source):
var convertImgToDataURLviaCanvas = function(url, callback) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL();
callback(dataURL);
canvas = null;
};
img.src = url;
}
convertImgToDataURLviaCanvas( 'http://some.com/images/1.jpg', function( base64_data ) {
console.log( base64_data );
} );
You can use this helper function to fetch a url and convert into dataURI.
function getDataUri(url, callback) {
var image = new Image();
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
// Get raw image data
callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''));
// ... or get as Data URI
callback(canvas.toDataURL('image/png'));
};
image.src = url;
}
Usage :
getDataUri($scope.facebookUserPicture.url, function(dataUri) {
// here you can set it up as the img src for the profile picture
$scope.profilePictureUri = dataUri;
});
You can also define this as a promise instead of a call back.
And finally, <img class="icon icon-home img-circle" ng-src="{{profilePictureUri}}">
Read more on this wonderful article by David Walash
This will fetch any resource as a blob and use filereader to convert it to a base64 data url. If you where to use canvas#toDataURL you would not get the same base64...
var blob = new Blob(['Simulate a url'])
var url = URL.createObjectURL(blob)
console.log("original blob size", blob.size)
fetch(url)
.then(res => res.blob())
.then(blob => {
var fr = new FileReader()
fr.onload = () => {
var b64 = fr.result
console.log(b64)
console.log("base64 size: ", b64.length)
$iframe.src = b64
}
fr.readAsDataURL(blob)
})
<iframe id="$iframe"></iframe>
There is better way to solve this problem and that is to store the raw binary you got in some way as a blob. Base64 is going to take up ~3x more data and since javascript string are utf16 it's going to take up 2x more memory...
Some good alternetives are indexedDB and Sandboxed Filesystem API

How can I get Image data or the path of cache of Image on WebPage in chrome or firefox?

I'm making an plugin(add-on) to upload image on any page.
I only can get the url of the image, but I want to get the image data or local cache of image.
by javascript on chrome or firefox.
I did it in my extension via canvas.
I created two functions. First getting image data from canvas using "toDataURL()" method (Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element (such as img)), and then using this data to get BLOB object.
function getImageDataURL(url) {
var data, canvas, ctx, blob;
var img = new Image();
img.onload = function() {
canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
try {
data = canvas.toDataURL();
blob = dataURIToBlob(data);
} catch(e) {
// Handle errors here
alert(e);
}
};
img.src = url;
};
function dataURIToBlob (dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var ab = [];
for (var i = 0; i < byteString.length; i++)
ab.push(byteString.charCodeAt(i));
return new Blob([new Uint8Array(ab)], { type: mimeString });
};
Here in the "blob" variable we have BLOB object with full image data.
You could use indexeDB (internal browser data base) that takes objets to store instead of URL. See Google dev tutorials for detailled use.

Categories