Convert local image to base64 string in Javascript - javascript

I'm trying to convert a local image to Base64 string. I am not using any HTML and simply need javascript which references the image's path within the code.
For instance, converting:
C:\Users\Work\Desktop\TestImage.jpg
into
/9j/4AAQSkZJRgABAQEASABIAAD/4QBKRXhpZgAASUkqAAgAAAADABoBBQABAAAAMgAAABsBBQABAAAAOgAAACgBAwABAAAAAgAAAAAAAAAAVOoqgJaYAABU6iqAlpgA/+IMWElDQ19QUk9GSUxFAAEBAAAMSExpbm8CEAAAbW50clJHQiBYWVogB84AAgAJAAYAMQAAYWNzcE1TRlQAAAAASUVDIH.....etc...
There are many posts like this but they all seem to utilize HTML in some way, in order to identify the file path. I'm hoping I can write a defined filepath within the javascript.
I tried this to no avail:
function convertImgToBase64()
{
var canvas = document.createElement('CANVAS');
img = document.createElement('img'),
img.src = C:\Users\Work\Desktop\TestImage.jpg;
img.onload = function()
{
canvas.height = img.height;
canvas.width = img.width;
var dataURL = canvas.toDataURL('image/png');
alert(dataURL);
canvas = null;
};
}
One example has the following html and javascript, but I'm hoping this can be consolidated together. Thanks for your support
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input type='file' id="asd" />
<br>
<img id="img" src="//placehold.it/1x1/" />
<div id="base"></div>
</body>
</html>
Javascript:
function el(id){return document.getElementById(id);} // Get elem by ID
function readImage() {
if ( this.files && this.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
el("img").src = e.target.result;
el("base").innerHTML = e.target.result;
};
FR.readAsDataURL( this.files[0] );
}
}
el("asd").addEventListener("change", readImage, false);\
Its demo found here

Try utilizing XMLHttpRequest() set responseType to Blob , use FileReader() at XMLHttpRequest onload event to read response as data URI
var xhr = new XMLHttpRequest();
xhr.open("GET", "/path/to/local/image/file", true);
xhr.responseType = "blob";
xhr.onload = function (e) {
console.log(this.response);
var reader = new FileReader();
reader.onload = function(event) {
var res = event.target.result;
console.log(res)
}
var file = this.response;
reader.readAsDataURL(file)
};
xhr.send()

Related

i couldn't get the download URL for the image

Get The download url and assign it to a variable
<html>
<head>
<h1>retrieve data</h1>
<h2 id=myimg></h2>
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
//firebase initialization
};
firebase.initializeApp(config);
</script>
<script>
storageRef.child('1.jpg').getDownloadURL().then(function (url) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function (event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
var img = document.getElementById('myimg');
img.src = url;
}).catch(function (error) {
});
</script>
</body>
</html>
i want the download url to be assigned
i want to retrieve the download URL from the firestorage and assign it to a variable
what modification should i do in this code to get the download URL of the uploaded image
Include the folder you're getting the image from 'pics/1.jpg' then remove the first section of your code that downloads the image and leave the bottom part that only assigns the URL to the image.
var storageRef = firebase.storage().ref();
storageRef.child('pics/1.jpg').getDownloadURL().then(function (url) {
var img = document.getElementById('myimg');
img.src = url;
}).catch(function (error) {
});

displaying images using file reader and blob

I want display a set of thumbnail images using fileReader api of javascript.I will send requests to my server and it will respond with a stream of bytes.I am sending requests through native xhr methods.But its not displaying any images.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="/js/jquery-2.1.1.js"></script>
<script>
var thumbURL = ['https://domainname.com/api/th/1','https://domainname.com/api/th/2','https://domainname.com/api/th/3','https://domainname.com/api/th/4','https://domainname.com/api/th/5','https://domainname.com/api/th/6'];
(function(){
for(var i=0;i<thumbURL.length;i++){
var oReq = new XMLHttpRequest();
oReq.open("GET", thumbURL[i]);
oReq.responseType = "blob";
oReq.onload = function(oEvent) {
if (this.status == 200) {
var fileReader = new window.FileReader();
fileReader.readAsDataURL(this.response);
var response=fileReader.result;
$("#thumbnails").append("<img src="+response+"></div>");
}
};
oReq.send();
}
})();
</script>
</head>
<body>
<div id="thumbnails"></div>
</body>
</html>
Any help will be greatly appreciated.Thanks in advance.
UPDATE:correct solution
<html>
<head>
<script type="text/javascript" src="/js/jquery-2.1.1.js"></script>
<script>
var thumbURL = ['https://domainname.com/api/th/1','https://domainname.com/api/th/2','https://domainname.com/api/th/3','https://domainname.com/api/th/4','https://domainname.com/api/th/5','https://domainname.com/api/th/6'];
(function(){
for(var i=0;i<thumbURL.length;i++){
var oReq = new XMLHttpRequest();
oReq.open("GET", thumbURL[i]);
oReq.responseType = "blob";
oReq.onload = function(oEvent) {
if (this.status == 200) {
var filereader=new window.FileReader();
filereader.readAsDataURL(this.response);
filereader.addEventListener("load",function() {
var response=filereader.result;
$("#thumbnails").append("<img src="+response+"></div>");
},false);
}
};
oReq.onerror=function(e){
alert("error");
};
oReq.send();
}
})();
</script>
</head>
<body>
<div id="thumbnails"></div>
</body>
</html>
The FileReader API is asynchronous so you have to add a load handler and when triggered, then add the result:
var fileReader = new window.FileReader();
fileReader.onload = function() { // need load handler
var response=this.result;
$("#thumbnails").append("<img src="+response+"></div>");
};
fileReader.readAsDataURL(this.response);
I would in any case recommend to skip the conversion part. Using the blob directly not only saves memory, but is much faster. You just have to create the image element manually, for example:
oReq.onload = function(oEvent) {
if (this.status === 200) {
var img = new Image;
img.src = (URL || webkitURL).createObjectURL(this.response);
$("#thumbnails").append(img); // todo: append the </div> separately
}
};

image does not download with it's own extension

I have used below code to download image with given name. But this seems does not download image with it's own image extension.
Here is HTML
<a id="btnDownload" href="www.mywebsite.com/images/myimage.jpg" onClick="downloadImage(www.mywebsite.com/images/myimage.jpg);" >download</a>
and code
function downloadImage(sUrl){
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest();
xhr.open('GET', sUrl, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
var res = xhr.response;
var blob = new Blob([res], {type:'image'});
url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = "My image name";
document.body.appendChild(a);
a.click();
};
xhr.send();
}
What i want is i want downloaded image with "My image name"."extension". Here image does have alternative extension like jpeg, png, gif.
But this code always download file without extension. Any changes here?
To get the extension in your example you could do:
a.download = "My image Name." + window.URL.split('.').pop();
Yet I would work with different data-attributes:
<html>
<!--
You can put the href and the name you want to see in different data attributes.
Also one can add IE support.
-->
<head>
<script>
//e:=<a [data-name] [data-href]>
function downloadMe(e){
var tF = e.getAttribute('data-name');
var tURL = e.getAttribute('data-href')
var tR = new XMLHttpRequest();
tR.open('GET', tURL, true);
tR.responseType = 'blob';
tR.onload = function(e){
var tB = this.response;
if(window.top.navigator.msSaveOrOpenBlob){
//Store Blob in IE
window.top.navigator.msSaveOrOpenBlob(tB, tF)
}
else{
//Store Blob in others
var tA = document.body.appendChild(document.createElement('a'));
tA.href = URL.createObjectURL(tB);
tA.download = tF;
tA.style.display = 'none';
tA.click();
tA.parentNode.removeChild(tA)
}
};
tR.send();
return false
}
</script>
</head>
<body>
<a href = '#' data-href = 'A.png' data-name = 'My Name.png' onclick = 'return downloadMe(this)'>download</a>
</body>
</html>

How to get image using XMLHttpRequest in javascript

I need to show a image which is generating in another page. I am using XMLHttpRequest to get the image from that page. Not able to do this please help.
Code Block
This is used to get image
Bitmap IMG = myPane.GetImage(700,700,92);
//Bitmap finalImage = new Bitmap(800, 800);
byte[] byteArray = new byte[0];
using (MemoryStream stream = new MemoryStream())
{
IMG.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
}
Response.Write(byteArray);
This is used to fetch that in javascript
function b() {
searchReq.onreadystatechange = ProcessResponse;
searchReq.open("GET", 'Default.aspx', true);
if (searchReq.overrideMimeType) {
searchReq.overrideMimeType('text/plain; charset=x-user-defined');
} else {
searchReq.setRequestHeader('Accept-Charset', 'x-user-defined');
}
searchReq.send(null);
}
function ProcessResponse() {
if (searchReq.readyState == 4) {
if (searchReq.status == 200) {
retval = "";
var img = document.getElementById("myimg");
img.src = "data:image/jpeg;base64," +(searchReq.responseText);
}
}
}
Thanks
Don't use XMLHttpRequest. Instead, just set the src of the img element to your .net script:
function b() {
var img = document.getElementById("myimg");
img.src = "Default.aspx";
}
If this doesn't work because the browser thinks it's the same image file just add some junk query param to the url:
img.src = "Default.aspx?q=" + Math.random();
Image is a binary data and you have to modify some attributes of your XmlHttpRequest object in order to process binary data.
Mozilla's website has a good documentation about this subject here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data
A code snippet from the above page does this:
var oReq = new XMLHttpRequest();
oReq.open("GET", "/myfile.png", true);
oReq.responseType = "blob";
oReq.onload = function(oEvent) {
var blob = oReq.response;
// ...
};
oReq.send();
You don't need to use XMLHttpRequest to retrieve your image. It can easily achieved by placing <img> tag like this:
<img src="myImageGenerator.aspx" alt="..." />
I'm assuming your script is on myImageGenerator.aspx page
Please note that myImageGenerator.aspx need to return the correct content type: image/png
You can do this in C#:
Response.Headers["Content-Type"] = "image/png";
Good luck

Read xml file, modify the values/add elements/attributes and save the xml how?

Using javascript, I want to read xml file from the disk, modify the values/add elements/attributes and save the xml back to disk.
Anyone knows here can i find examples that works with IE and Firefox? I allready find examples to read, now changing values that's the problem.
Thanks
Assuming you are trying to read and write to disk from the browser and not node.js,
the first step is to use an input tag of type file to get access to the file system.
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input type="file" id="input" accept="text/xml">
<script src="script.js"></script>
</body>
As soon as a file is selected we want to extract the blob from the element.
A good moment to do that is during the change event.
const input = document.querySelector('#input');
input.addEventListener('change', () => {
const file = input.files.item(0);
});
There is more than one way to parse the blob into a tree of elements.
Here I took advantage of the fact that the browser parses xml documents in HTTP requests.
function blobToDocument(blob, callback) {
const url = URL.createObjectURL(blob);
const request = new XMLHttpRequest();
request.open('Get', url);
request.responseType = 'document';
request.addEventListener('load', () => {
callback(request.response);
});
request.send();
}
After the blob has been parsed we can manipulate it like we would manipulate the DOM tree.
function editDocument(document) {
const element = document.createElement('editor');
element.textContent = 'JavaScript';
document.firstChild.appendChild(element);
return document;
}
In order to save the file to disk we need to reverse the process of parsing,
converting the tree of elements back to a string.
function documentToString(document) {
const serializer = new XMLSerializer();
return serializer.serializeToString(document);
}
The only thing left is to send the file back to disk.
To achieve this we can trigger a click event on a link with our modified file.
function download(string, mime) {
const blob = new Blob([string], { type: mime });
const a = document.createElement('a');
const url = URL.createObjectURL(blob);
a.href = url;
a.download = 'document.xml';
a.click();
}
Here is the complete code
const input = document.querySelector('#input');
input.addEventListener('change', () => {
const file = input.files.item(0);
blobToDocument(file, (xmlDocument) => {
editDocument(xmlDocument);
download(documentToString(xmlDocument), "text/xml");
});
});
function blobToDocument(blob, callback) {
const url = URL.createObjectURL(blob);
const request = new XMLHttpRequest();
request.open('Get', url);
request.responseType = 'document';
request.addEventListener('load', () => {
callback(request.response);
});
request.send();
}
function editDocument(document) {
const element = document.createElement('editor');
element.textContent = 'JavaScript';
document.firstChild.appendChild(element);
return document;
}
function documentToString(document) {
const serializer = new XMLSerializer();
return serializer.serializeToString(document);
}
function download(string, mime) {
const blob = new Blob([string], { type: mime });
const a = document.createElement('a');
const url = URL.createObjectURL(blob);
a.href = url;
a.download = 'document.xml';
a.click();
}
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input type="file" id="input" accept="text/xml">
<script src="script.js"></script>
</body>

Categories

Resources