How to convert BinaryString to jpg - javascript

function upload(file){
var reader = new FileReader();
reader.onload = function (evt) {
uploadComplet(file.name, evt.target.result);
}
reader.readAsBinaryString(file.fileBlob);
}
function downloadComplet(binaryString){
var newFile = new File( [binaryString] , "newName.jpg");
var downloadUrl = URL.createObjectURL(newFile);
var downloadButton = document.createElement('a');
downloadButton.setAttribute('href', downloadUrl);
downloadButton.setAttribute('download', newFile.name);
downloadButton.setAttribute('class', 'button');
downloadButton.innerText = 'Download: ' + newFile.name;
downloadButton.click();
}
I uploaded the BinaryString of the image file and downloaded it as it was. But I could not bring in the correct image. What should I do?

Take this as an example:
var img = document.createElement('img');
img.src = 'data:image/jpeg;base64,' + btoa('your-binary-data');
document.body.appendChild(img);

Related

How to call a function that gives a url, which is then used to store and display an image using FileReader

I am new to coding in javascript, I have been tasked as an excersise using some pre-existing functions to create an image item using a given url. I need to read the image, store it in local storage and then display it on the screen. The only functionI need to add too is process file. I am stuck and cannot get it to display the image. I get an error saying that the path does not exist. Below is my code, any guidance to what I am doing wrong? I feel like I am very close but doing something funamendatly wrong.
function addImageEntry(key, url) {
var imgElement = new Image();
imgElement.alt = "Photo entry";
imgElement.src = url;
addSection(key, imgElement);
}
function makeItem(type, data) {
var itemObject = { type: type, data: data };
return JSON.stringify(itemObject);
}
function processFile(event) {
function addImage(url) {
var key = "diary" + Date.now();
addImageEntry(key, url);
var imgElement = new Image();
imgElement.src = url;
var item = makeItem("image", imgElement.src);
localStorage.setItem(key, item);
}
var inputElement = event.target;
var fileObject = inputElement.files[0];
var reader = new FileReader();
reader.addEventListener("load",addImage);
url = reader.readAsDataURL(fileObject);
event.target.value = "";
}
The url = reader.readAsDataURL(fileObject) won't store the image data.
It stores in reader.result.
Use imgElement.src = reader.result.
document.querySelector('input[type="file"]').addEventListener('change', processFile)
function processFile(event) {
var fileObject = event.target.files[0]
var reader = new FileReader()
reader.addEventListener('load', addImage)
reader.readAsDataURL(fileObject)
function addImage() {
var imgElement = new Image()
imgElement.src = reader.result
document.body.append(imgElement)
}
}
Amend:
function addImage(event) {
// use reader.result is ok too
localStorage.setItem('myimage', event.target.result)
}
function addImageEntry() {
var imgElement = new Image()
imgElement.src = localStorage.getItem('myimage')
imgElement.style.display = 'block'
document.body.append(imgElement)
}

Need help to generate three blocks using loop

Following 3 block of code, want to generate using loop/array to make short code.I know use of loop is not a big thing, but for me its difficult to change counter with variable "openFile", I want counter increment with variable "openFile" like openFile1, openFile2 and openFile3 with each iteration of loop.
$(function() {
var openFile1 = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('img1');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
var openFile2 = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('img2');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
var openFile3 = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('img3');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
});
Just create a function that takes count as arg and return a function that takes just event as arg. due to closure, the value of 'count' given when calling openFile with a given value of count will be used for the inner function.
var openFileFunc = function(count) {
return
function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('img'+(count+1));
output.src = dataURL;
};
reader.readAsDataURL(input.files[count]);
};
}
Now you can get the three functions equivalent to what you did by calling a map like this:
var functions = [1,2,3].map(openFileFunc)
Each function in this array is the same as what you had.
var openFile = function(arrOfCount){
var reader;
for(i=0;i<arrOfCount;i++){
reader= new FileReader();
return function(event){
var input = event.target;
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('img'+(i+1));
output.src = dataURL;
};
reader.readAsDataURL(input.files[i]);
}
}
}
May be this will work for you.
function callFunctionNtimes(totalCount){
for(start=1;i<=totalCount;i++)
{
var filevar = 'openFile'+start;
filevar = function(event)
{
var input = event.target;
var reader = new FileReader();
reader.onload = function()
{
var dataURL = reader.result;
var output = document.getElementById('img'+start);
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
}
}
//to call n time below function
var totalCount = 3;
callFunctionNtimes(totalCount);
I have tried to generalize code
var allImages = document.getElementsByClassName("my-images");
for (var i = 0; i < allImages.length; i++) {
var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = allImages[i];
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
}
But still it seems you have 3 file upload controls and you want to display preview for each, is it so?

How to to base 64 encode in two images in same file

Here i have two form fields , in this i want to convert the base 64 encode from image,and after that i want to pass in JSON Format to next URL, i tried like this but i am not getting ,some time i am getting one filed value (encoded value) uncaught error property_img , i don't know how to do anyone help me pls
var files = document.getElementById('floorplan_img').files;
if (files.length > 0) {
var file = files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
console.log(reader.result);
var base64 = reader.result;
var str = base64;
var arr = str.split(",");
var floor_img = arr[1];
console.log(floor_img);
};
reader.onerror = function(error) {
console.log('Error: ', error);
};
}
var files1 = document.getElementById('upload_properties').files;
if (files1.length > 0) {
var file1 = files1[0];
var reader1 = new FileReader();
reader1.readAsDataURL(file1);
reader1.onload = function() {
var base64_img = reader1.result;
var str_64 = base64_img;
var arr_str = str_64.split(",");
var property_img = arr_str[1];
console.log(property_img);
};
reader1.onerror = function(error) {
console.log('Error: ', error);
};
}
<input type="file" id="floorplan_img">
<input type="file" id="upload_properties">
Try this:
var reader = new FileReader();
reader.onload = function(event) {
var src= event.target.result;
console.log(src);
};

JavaScript set value to variable defined in parent function

i want to return imageSize but it is returning undefined. i am confused i have tried many things. in the alert i am getting size.
getImageSize : function(file) {
var reader = new FileReader();
var image = new Image();
var imageSize;
reader.readAsDataURL(file);
reader.onload = function(_file) {
image.src = _file.target.result;
image.onload = function() {
imageSize = ~~(file.size/1024) +'KB';
alert(imageSize);
};
};
return imageSize;
}
Since you are loading the image asynchronously, you cannot return the size directly. The best you can do is pass in a call-back function to be called when the size is available:
getImageSize : function(file, callback) {
var reader = new FileReader();
var image = new Image();
var imageSize;
reader.readAsDataURL(file);
reader.onload = function(_file) {
image.src = _file.target.result;
image.onload = function() {
imageSize = ~~(file.size/1024) +'KB';
callback(imageSize);
};
};
}

Creating a Blob from an external image url

I have an file input that i used to get a file and turn it into a blob. Is there anyway I can get an external image url and turn that into a blob? Here is the code I am using to do it with just a file from a <input type="file" />:
//Process the file and resize it.
function processfile(file) {
if (!(/image/i).test(file.type)) {
alert("File " + file.name + " is not an image.");
return false;
}
// read the files
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function (event) {
// blob stuff
var blob = new Blob([event.target.result]); // create blob...
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob); // and get it's URL
// helper Image object
var image = new Image();
image.src = blobURL;
image.onload = function () {
for (var x = 0; x < self.ThumbSizes.length; x++) {
// have to wait till it's loaded
var resized = resizeMe(image, self.ThumbSizes[x]); // send it to canvas
var resized_blob = dataURItoBlob(resized);
uploadFile(resized_blob, self.ThumbSizes[x].Name);
}
}
};
Instead of passing a file through I wanted to be able to structure this code to pass a image url and convert it into a blob.
I hope it helps you. (I didn't run it.)
function processfile(imageURL) {
var image = new Image();
var 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);
canvas.toBlob(function(blob) {
// do stuff with blob
});
};
image.onload = onload;
image.src = imageURL;
}

Categories

Resources