I have a URL of an image that when I set the src of an img to, the img changes to the image on the URL.
I want to download this image as a string so I can store it in local storage.
So I get the image data using XMLHttpRequest and this returns data that looks like this:
�T��ǁ�Y�k����De,�GV��<A:V��TɕH'�:A�
a��.e��E�ʓu�|���ʘ�*GN�'��қ��u�� ��c��]�
�.N���RH!�O�m�Aa���Զ�0U #Pɬ��:�շ���
p�;2��Z���H����¯��P�un>�u�uj��+�쨯
��Z��֦DW>U����.U:V�{�&(My��kύO�S�������e��ԃ����w�
1��j2�Ŭo�#����>ɛP���:E�o}\O���r ��Ύ�
ob�P|b��/e�\#����k>��?mr<�ƭ�0~����f����\�i�^���ޟj��ٙI&=��B���N��(�N��C�kO�o3e�az�G
�|�����AO�A�6�2
�H�^�5��$�Ѭ
\��|x�+�0 ͤ,n�|������B����
w4ɞG�Q!�"�yb#�[A��\m)��߂�dA�h�.��6����q�αA0�bO��20*�LVX�<`Rv�W�6�f'hF���V���n`̌v�7�Ν��OI|���Ԙ�uoqk���n����g��a��ӗ>���Ԏt��
I'm not sure what format this data is in. It could be Base64 based on some Google searching but not 100% sure. This is just what I get when I console.log it. The image data string has a length of 109095. The console freezes when I log this string, can't figure out why.
I then try to set the src of the img in javascript like this:
x.src = "data:image/jpg;base64," + imageData;
And it doesn't work.
If you want a dataURI version of your image, the best way is to set the XHR.responseType to "blob", and read the resulted response blob with a FileReader :
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(){
var reader = new FileReader();
reader.onload = function(){
img.src = this.result;
result.textContent = this.result;
};
reader.readAsDataURL(this.response);
};
xhr.open('GET', 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png');
xhr.send();
<img id="img"/>
<p id="result"></p>
Of course, you'll have to make the call to the same origin, or to an open server (such as wikimedia one).
You should convert the image to base64 first.
Try this link
How to convert image into base64 string using javascript
Related
I am trying to download a file in a service worker. The file came from a blob.
I already know that i can download a blob by doing this
var urlCreator = window.URL || window.webkitURL;
var blobURL = urlCreator.createObjectURL(blob, { type: "octet/stream" });
or by using something like FileSaver.js
But today, i am trying to "render" the bytes array of the blob in the page and force the browser to download the document.
Why ?
I am trying to do that because, some browser that i am trying to reach do not support url like "blob:https:......"
So i try to find a way to render the bytearrays of my blob directly in javascript.
I know that i can push headers with worker, but not sure that is the right strategie.
I also try something like that
var xhr = new XMLHttpRequest();
xhr.open('GET', obj.URL, false);
xhr.overrideMimeType("application/octet-stream");
//xhr.setRequestHeader("Accept", "application/octet-stream");
xhr.responseType = "arraybuffer";
xhr.onload = function (e) {
self.Response(xhr.response);
//if (this.status == 200) {
// var myBlob = this.response;
// // myBlob is now the blob that the object URL pointed to.
//}
};
xhr.send();
In my worker.js
ps: Please avoid to told me, send you base64 blob content to your server and send back the file to the browser, i would like to find a pure javascript solution.
Is it possible ?
This is a continuation to my previous question but the issue is new and the solution from that question didn't help. This is a new question.
Here's the link to my previous question where I asked how to convert canvas to an image: javascript- unable to convert canvas to image data
And I'm hoping to get the base64 encoded string of the image which I can send to a PHP service via AJAX call and PHP service is gonna convert it to image and move it to a specified directory.
Function that converts canvas to image
function convertCanvasToImage(canvas)
{
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
This is the form I created:
var url = 'url to php service';
var file = dataURL; //this is the image url that i'm sending
console.log(file);
var formdata = new FormData();
formdata.append("base64image", file);
formdata.append('csrf_test_name',csrf_token);
var ajax = new XMLHttpRequest();
ajax.addEventListener("load", function(event) {
uploadcomplete(event);
}, false);
ajax.open("POST", url);
ajax.send(formdata);
I tried console.log() the image that canvas returned and this is what I obtained:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAYAAAA10dzkAAAgAElEQVR4nGzbZ3Mba5au6fqvJ2JiTs/pPtVV20j0sOm9T3iARqI3IOi9SIoGHqATJe29q/v8jXs+QMWeHT0fnkgGyUgCiRfIi2ut9y9OqYGZ3yKqHWHlttFiCz1nE8Q+XuDiuSb5XEBccYgrDv6si5ZTMOZMzHkLMS6gFspI8TxiOEfkfCS0P1AM1lmcPaJYPcbyNvDDHUqVU5zdTaS1j4hFm3Erg5bxCK0KxXiWUm6OcLaAW46xCzZBNcAOF3FzK8TBIoG7QC7v4AUalqdRquVQZxeQa/PYc2vYc2uUnWUCuYovR+TMEoEVY8oOnhES2jlKVo2au0DZXiVSF/DciDDMUyjOEuerGGqJYm6VaG6DhBahOyW8eB4rrBGVl5BmZ5FmZ1HyLlrJZ37ep1jUyXseOdel7FWpBrMUgwXy3ixGJGLlZLRIxipoh...Hd7sRkseD2ebFF/Bj9btUYEnDzGHRy57XgcDiw2WyYDPdYzFp0dgvXBh0XeiPmYBit2YzBbufR4uDR4kBrd3BtNHHvs6ty3HJru+beoUXn0vPgNaD1Gbl1udFYbWhMFlU2E7du+zTmRWt75MGqw+axYvNYebRpMbmNaF0OzEE/+nQAXcrHpeBAk7BzJTm4zXg4Kdq4afq4nGS4fslyO85x1IizEbWwJzo5Lzu4bfk560Y5agY57SfYawS57sS4akfRFJxc5B1cl7XcVh85Gfo47HvYaFvY6ds5Hvg5GQY4bUY5rofQtAUumgk0XVXXozSXQxX+rnsSt20nmrqFG+URbdHMVSOGphbmrCNw1hG46Dg4aaoxP0c1B0dVD7sFO0cFG0cFG+fKNSeyhjPhBI10zmnqnPP0xRQAD1Pqs7CSV7VV3mCztM5Rbpnz8joXHSPXfQuXPQ9XAy9noxgXE4HT/8pz8X/L/D+QyAVhXuteXgAAAABJRU5ErkJggg==">
It has image tag. Maybe it's because of that; when I pass it to PHP service, it's not able to convert it. This is what it returned me when I debugged
object HTMLImageElement
I tried to convert the above mentioned image tag to base64 using a function like given below but it failed.
function encodeImageFileAsURL(cb) {
return function(){
var file = this.files[0];
var reader = new FileReader();
reader.onloadend = function () {
cb(reader.result);
}
reader.readAsDataURL(file);
}
}
Can anyone help me understand what i am missing here? Thanks a lot!
Reference:
https://davidwalsh.name/browser-camera
https://davidwalsh.name/convert-canvas-image
You already have a data URI at the src of the <img> element at variable image. Pass the value of the src of the <img> element to php, not the html <img> element.
var file = image.src; //this is the image url that i'm sending
I'm retrieving previously uploaded image binary content. Now I need to convert it back to a downloadable image. Here is the code I used.
var xhr = new XMLHttpRequest();
xhr.open('GET',httpUrl+ url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
alert(this.response);
var responseArray = new Uint8Array(this.response);
alert('VAL' + responseArray.length);
var base64 =btoa(uint8ToString(responseArray));
window.open("data:image/jpeg;base64," + base64) ;
};
xhr.send();
What could be the issue here? a new window opens up but the image is not appearing which means the content is not correct. Also i checked with an online converter (using the base64 string i get) and it also doesn't show the image. So basically my conversion is wrong.
I have currently been trying to hash an image from my browser using javascript. However, I've been hashing a string of the dataURL or the pixel data that I've been retrieving from the canvas element in HTML. This is obviously not the same as hashing the raw data of the image which is what I would like to do.
For example the data that would be used for the same image in the php hash file function.
Does anybody know how I can access this raw image data using javascript to get a hash value that would be equivalent to the result hash I get from PHP hash_file($file)?
Thanks!
You can get the raw data of an image with an XHR request to that image file location.
var xhr = new XMLHttpRequest();
xhr.open('GET', '/my/image/file.png', true);
xhr.responseType = 'arraybuffer'; // this will accept the response as an ArrayBuffer
xhr.onload = function(buffer) {
var words = new Uint32Array(buffer),
hex = '';
for (var i = 0; i < words.length; i++) {
hex += words.get(i).toString(16); // this will convert it to a 4byte hex string
}
console.log(hex);
};
xhr.send();
After that, you can use whatever hashing algorithm you'd like. Here's a library of them: https://code.google.com/p/crypto-js/
I'm loading a jpeg image from my server in binary format via XMLHttpRequest (I need it that way). It's not base64 encoded.
Is it possible to turn it to an img object with javascript?
Thanks
If the character encoding of the XMLHttpRequest has been set to something that won't change the binary data, or you've set the response type, you can then run .responseText through btoa (putting it in base64 and letting you assign it as a data URI) or access .response for the binary data, respectively.
Assuming your instance is named xhr and you're using the charset method before xhr.send but after xhr.open do
xhr.overrideMimeType("text/plain; charset=x-user-defined");
then when you're 200 OK
var dataURI = 'data:image/jpeg;base64,' + btoa(xhr.responseText);
Which you can then set as a src of an <img>.
Again assuming xhr, this time .response method; between .open and .send,
xhr.responseType = "arraybuffer";
Then at 200 OK
var arrayBufferView = new Uint8Array(xhr.response), // can choose 8, 16 or 32 depending on how you save your images
blob = new Blob([arrayBufferView], {'type': 'image\/jpeg'}),
objectURL = window.URL.createObjectURL(blob);
Which you can then set as a src of an <img>. Example