How to convert an image into a Base64 string in a file? - javascript

I want to select multiple images and convert them to Base64 strings. I pushed the files into one array. My requirement is that after converting into Base64 strings, I want to push them into an array. I am not able to convert the images to Base64 strings.
$("input[name=property_images]").change(function() {
var names = [];
for (var i = 0; i < $(this).get(0).files.length; ++i) {
names.push($(this).get(0).files[i].name);
}
console.log(names);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="file" name="property_images" multiple="multiple" />

change your function to store the base64 value
$(document).ready(function(){
$("input[name=property_images]").change(function() {
var imgBase64Arr = [];
var files = this.files;
for (var i = 0; i < files.length; i++) {
(function(i){
var FR = new FileReader();
FR.onload = function(e) {
imgBase64Arr.push( e.target.result );//adding base64 value to array
if(i === files.length -1)//after all files are porcessed
submitData(imgBase64Arr)
};
FR.readAsDataURL(files[i]);
})(i);
}
});
function submitData(imgBase64Arr){
console.log(imgBase64Arr);
}
});

Here we have single image to convert base64 string.
function readFile() {
if (this.files) {
for(i=0;i<this.files.length;i++)
{
var FR= new FileReader();
FR.onload = function(e) {
//document.getElementById("img").src = e.target.result;
//document.getElementById("b64").innerHTML = e.target.result;
//$("#b64").append("<div></div>").html(e.target.result);
$('<img src="'+e.target.result+'" />').appendTo('#show-image');
$('<p>'+e.target.result+'</p>').appendTo('#text-image');
};
FR.readAsDataURL( this.files[i] );
}
}
}
document.getElementById("inp").addEventListener("change", readFile, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="inp" type='file' multiple>
<div id='show-image'></div>
<div id='text-image'></div>

Related

convert image path to byte array javascript

i want to convert image to byte array javascript, here i have upload image from the gallery , below i mention what i have tried
<input type="file" name="images" id="fileUploadExactequipment" data-value="0" class="imageUpload1"> <span id="lblError" style="color: red;" onclick="imageValidation1(this);"></span></td><td>
var files = $('#fileUploadExactequipment')[0].files[0];
var exactImageByteArray= fileToByteConverter(files);
function fileToByteConverter(imagePath){
debugger
var reader = new FileReader();
var fileByteArray = [];
reader.readAsArrayBuffer(imagePath);
reader.onloadend = function (evt) {
if (evt.target.readyState == FileReader.DONE) {
var arrayBuffer = evt.target.result,
array = new Uint8Array(arrayBuffer);
for (var i = 0; i < array.length; i++) {
fileByteArray.push(array[i]);
}
}
return fileByteArray;
}
}
is this correct or not

How to load image from directory, then show onclick

I am trying to have a function which has functions that do the following.
One function to store the files i get with input into the parent functions loadedimages array(loadimages).
One function to show those files in the correct component(showLoadedImages).
And one function to make the correct img file appear on the correct component.
The last function is what i want it to be like(it does not work).
The other two seem ok.
The problem i have is how to make the last function work while using the loadedimages array. You can change what i store in the array , i wouldnt mind.
Here is the JS code:
function imgviewer() {
"use strict";
var loadedimages = [];
var lidivs = [];
function loadimages() {
var files = document.getElementById("images").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.name.match(/\.(jpg|jpeg|png|gif)$/)) {
alert('THERE IS NO IMAGE IN THIS DIRECTORY.');
break;
}
loadedimages.push(file);
}
}
function showLoadedImages(elem) {
loadimages();
var ld = loadedimages;
//var files = getLoadedImages(); //filelist obj
for (var i = 0; i < ld.length; i++) {
var file = ld[i];
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
// Render thumbnail.
var span = document.createElement(
'span');
span.innerHTML = [
'<img class="tile" src="',
e.target.result,
'" title="', encodeURI(
file.name), '">'
].join('');
document.getElementById(elem).insertBefore(
span, null);
lidivs.push(span);
};
})(file);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
}
}
function showImage(index, elem) {
var chosenFile = loadedimages[index];
document.getElementById(elem).src = chosenFile;
}
document.getElementById('images').addEventListener('change', function(){
showLoadedImages("main");
}, false);
}
And some HTML
<form name="uploadForm">
<input id="images" type="file" webkitdirectory mozdirectory directory name="myFiles"
multiple/>
<span id="list"></span>
</form>
<div id="sidebar1"><img id="willchange" src="images/railaythailand.jpg" width="1200" height="832" alt=""/></div>
<div id="main"></div>
When i call showLoadedImages("main") the images are shown in main div. I want to be able to click those images so that they appear on "willchange" .
This does what you asked for. There are a number of other issues with your code that you might want to address, starting with the images are not thumbnails at all (and shrunken images take just as long to load as the original), but perhaps I'm missing something.
"use strict";
var loadedimages = [];
var lidivs = [];
function loadimages() {
var files = document.getElementById("images").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.name.match(/\.(jpg|jpeg|png|gif)$/)) {
continue;
}
loadedimages.push(file);
}
loadedimages.length || alert('THERE IS NO IMAGE IN THIS DIRECTORY.');
}
function showLoadedImages(elem) {
loadimages();
var ld = loadedimages;
//var files = getLoadedImages(); //filelist obj
for (var i = 0; i < ld.length; i++) {
var file = ld[i];
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
// Render thumbnail.
var span = document.createElement(
'span');
span.innerHTML = [
'<img data-index="',
lidivs.length,
'" class="tile" src="',
e.target.result,
'" title="', encodeURI(
file.name), '">'
].join('');
span.addEventListener("click", foo );
document.getElementById(elem).insertBefore(
span, null);
lidivs.push(span);
};
})(file);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
}
}
function showImage(index, elem) {
document.getElementById(elem).src = lidivs[index].children[0].src;
}
function foo(event) {
showImage(event.target.dataset.index, "willchange");
}
function show() {
showLoadedImages("list");
}
function init() {
document.getElementById("images").addEventListener("change", show, false);
}
document.addEventListener( "DOMContentLoaded", init, false );
<body>
<form name="uploadForm">
<input id="images" type="file" webkitdirectory mozdirectory directory name="myFiles"
multiple/>
<span id="list"></span>
</form>
<div id="sidebar1"><img id="willchange" src="images/railaythailand.jpg" width="1200" height="832" alt=""/></div>
</body>

encode/decode image with base64 image

I have created the multiple file (image) upload option. And I have encoded the image file and stored them in an array.
I am trying to encode and decode an image. I am using the FileReader's readAsDataURL method to convert the image to base64.
Now I want to Convert the image(Original file) for the download option.
My code is;
<html>
<body>
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" multiple />
<div id="imgTest"></div>
<script type='text/javascript'>
function encodeImageFileAsURL(index) {
var filesSelected = document.getElementById("inputFileToLoad").files;
index = index || 0;
if (filesSelected.length > 0 && index < filesSelected.length) {
var fileToLoad = filesSelected[index];
var fileReader = new FileReader();
fileReader.onloadend = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").appendChild(newImage);
if (index < filesSelected.length) {
encodeImageFileAsURL(index + 1)
}
console.log(srcData);
}
fileReader.readAsDataURL(fileToLoad);
var sourceArray = new Array(); // put this before the function delaction
fileReader.onloadend = function (fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
sourceArray.push(srcData);
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").appendChild(newImage);
if (index < filesSelected.length) {
encodeImageFileAsURL(index + 1)
}
alert( fileLoadedEvent.target.result);
var imgSrc= fileLoadedEvent.target.result;
console.log(imgSrc);
//console.log(sourceArray);
//alert( fileLoadedEvent.target.result);
}
}
}
</script>
</body>
</html>
How to Encode and Decode Uploaded image file(multiple) using input type ="File"

how to store multiple encoded values in multiple variables

I have given multiple upload file option but it is storing everything in one variable but i am not getting how to store seperate file encoded value in a seperate variable. It should create variable and store encoded value according to file upload.
<html>
<body>
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" multiple />
<div id="imgTest"></div>
<script type='text/javascript'>
function encodeImageFileAsURL(index) {
var filesSelected = document.getElementById("inputFileToLoad").files;
index = index || 0;
if (filesSelected.length > 0 && index < filesSelected.length) {
var fileToLoad = filesSelected[index];
var fileReader = new FileReader();
fileReader.onloadend = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").appendChild(newImage);
if (index < filesSelected.length) {
encodeImageFileAsURL(index + 1)
}
console.log(srcData);
}
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
</body>
</html>
You may save the variable into an array, then access it whenever you want.
var sourceArray = new Array(); // put this before the function delaction
fileReader.onloadend = function (fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
sourceArray.push(srcData);
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").appendChild(newImage);
if (index < filesSelected.length) {
encodeImageFileAsURL(index + 1)
}}
console.log(sourceArray);

Read text file using FileReader

I've written the following code in an attempt to read the contents of a .txt file
<!DOCTYPE html>
<html>
<input type="file" id="files" name="file" />
<div id="container" style="height: 500px; min-width: 500px"></div>
<script>
function handleFileSelect(evt)
{
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++)
{
var reader = new FileReader();
reader.onload = (function(theFile)
{
var contents = theFile.target.result;
var lines = contents.split('\n');
})(f);
reader.readAsText(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</html>
Using firebug I set a break on var contents = theFile.target.result; but nothing is being returned. Can anyone spot what's wrong?
Thank you
Try (onload with closure):
function handleFileSelect(evt)
{
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++)
{
var reader = new FileReader();
reader.onload = (function(reader)
{
return function()
{
var contents = reader.result;
var lines = contents.split('\n');
//////
document.getElementById('container').innerHTML=contents;
}
})(reader);
reader.readAsText(f);
}
}
Or (without closure):
function handleFileSelect(evt)
{
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++)
{
var reader = new FileReader();
reader.onload = function(event)
{
// NOTE: event.target point to FileReader
var contents = event.target.result;
var lines = contents.split('\n');
//////
document.getElementById('container').innerHTML=contents;
};
reader.readAsText(f);
}
}
my example
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewText() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadTextValue").value = oFREvent.target.result;
document.getElementById("obj").data = oFREvent.target.result;
};
};
jQuery(document).ready(function(){
$('#viewSource').click(function ()
{
var text = $('#uploadTextValue').val();
alert(text);
//here ajax
});
});
</script>
<object width="100%" height="400" data="" id="obj"></object>
<div>
<input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
<input id="uploadText" style="width:120px" type="file" size="10" onchange="PreviewText();" />
</div>
Source file
</body>
</html>

Categories

Resources