I am streaming ArrayBuffers from a python server and am trying to interpret each one as an image on the client side with javascript. They are being received as arraybuffers in javascript. However I cant get them to be readable by the image tags src attribute. I have tried generating them into Blob objects then using window.URL.createObjectURL(blob). That hasnt work either.
The blob url looks like this blob:null/e2836074-64b5-4959-8211-da2fc24c35a6 is that wrong?
Does any have any suggestions/know a solution.
Thanks a lot.
var arrayBuffer = new Uint8Array(stream.data);
var blob = new Blob([arrayBuffer], {type: "image/jpeg"});
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL( blob );
console.log(imageUrl);
img.src = imageUrl;
array buffer image
If you have any control over things, you should use the responseType of blob on your Javascript call. This will let you use the data you are getting from your server directly instead of attempting to access it via an ArrayBuffer
See the following fiddle for an example: https://jsfiddle.net/ort74gmp/
// Simulate a call to Dropbox or other service that can
// return an image as a blob
var xhr = new XMLHttpRequest();
// Use JSFiddle logo as a sample image to avoid complicating
// this example with cross-domain issues.
xhr.open( "GET", "https://fiddle.jshell.net/img/logo.png", true );
// Ask for the result as an ArrayBuffer.
xhr.responseType = "blob";
xhr.onload = function( e ) {
var blob = this.response;
var reader = new FileReader();
reader.onload = function() {
var dataURL = reader.result;
document.querySelector('#photo').src = dataURL;
}
reader.readAsDataURL(blob);
};
xhr.send();
Related
I'am able to convert my pdf files into blob. But what i want to do is the opposite by converting it from blob to pdf.
Here is my code converting it from pdf to blob. I just need some advice where i can return from blob to pdf.
var xhr=new XMLHttpRequest();
xhr.open("GET","./template.pdf");
xhr.responseType="arraybuffer";
xhr.onload = function (e){
var blob = new Blob([xhr.response]);
var url = URL.createObjectURL(blob)
console.log(url);
var embed=document.getElementById("template");
embed.src = url;
}
xhr.send();
The result will return a blob from console=> blob:http://localhost:8081/d42939da-e318-4d88-b46f-8240efaa7b1c and once i paste this on the url, it will show me a huge blob text
You can set the content type when creating the blob to tell it is a pdf.
var blob = new Blob([xhr.response], { type: 'application/pdf' });
I have Blob, which stored in db and i take it from database with java server like this:
Entity.java
#Column(name = "img")
private Blob img;
public Blob getImg() {
return img;
}
public void setImg(Blob img) {
this.img = img;
}
Repository.java
#Transactional
#Query(value = "SELECT img FROM articles WHERE category = ?", nativeQuery = true)
//Blob findP(String category);
Blob findPic(String category);
Controller.java
#RequestMapping(value="/Pic_test")
#ResponseBody
public Blob getPics() throws SQLException, IOException {
return remindRepository.findPic("Java");
}
Then I receive it with Javascript to image it:
function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
toDataURL('http://localhost:8080/articles/Pic_test', function(dataUrl) {
var display = document.getElementById('display');
var url = window.URL.createObjectURL(new Blob([dataUrl]));
var img = new Image();
img.src = url;
document.getElementById("demo").innerHTML = img.src;
})
However, if I call my "img" Blob in java code, i have an error in server, but if I call it byte[], my picture is not shown just.
I can't comment the java part since I know nothing about it, but for the javascript one, what you do is... not correct.
You don't seem to understand what is a data URL, nor what you are doing here.
So a data URL is a string, made of an header and of some file content (data:|mime/type;|file-content).
A data URL is an URL that points to itself, useful to embed data that should normally be served from network.
Quite often, the file content part is encoded as base64, because the URI scheme is limited in its set of allowed characters, and that binary data couldn't be represented in this scheme.
Now let's see what you are doing here...
You are downloading a resource as a Blob. That's good, Blob are perfect objects to deal with binary data.
Then, you read this Blob a data URL. Less good, but I can see the logic, <img> can indeed load images from data URLs.
But then from this data URL string, you create a new Blob! This is completely wrong. The Blob you just created with new Blob([dataUrl]) is a text file, not your image file in any way. So yes, the data is still hidden somewhere in the base64 data which is itself in the data URL, but what your poor <img> will see when accessing the data hooked by the Blob URI is really just text, data:image/png;base64,iVBORw0... and not at all �PNG... like its parsing algo can read.
So the solution is quite easy: get rid of the FileReader step. You don't need it.
var xhr = new XMLHttpRequest();
xhr.open('get', 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png');
xhr.responseType = 'blob';
xhr.onload = display;
xhr.send();
function display(evt) {
// we did set xhr.responseType = "blob"
var blob = evt.target.response; // so this is a Blob
// hence, no need for anything else than
var url = URL.createObjectURL(blob);
var img = new Image();
img.src = url;
document.body.appendChild(img);
}
And if I may, all your thing could also just be
document.getElementById('display').src = 'http://localhost:8080/articles/Pic_test';
I am trying to get base64 of the image in my HTML by using HTML FileReader but for some reasons it doesn't work. My html is:
<div></div>
And script is:
var file = "http://mw2.google.com/mw-panoramio/photos/medium/23830229.jpg";
var reader = new FileReader();
reader.onload = function (e) {
iconBase64 = e.target.result;
$('div').append(iconBase64);
}
Can anybody help me?
I'll have to go against the majority and tell that you can actually get it without a canvas.
The statement that FileReader can't read external files is not completely true :
You can give it a blob as source.
So you can convert your external resource to a Blob object, using XMLHttpRequest
making it available from the local machine so the above statement isn't completely false either,
then get its dataURL from the FileReader.
var file = "http://mw2.google.com/mw-panoramio/photos/medium/23830229.jpg";
var xhr = new XMLHttpRequest();
xhr.onload = function(e) {
getDataURL(this.response);
};
xhr.open('GET', file, true);
// the magic part
xhr.responseType = 'blob';
xhr.send();
function getDataURL(blob) {
var reader = new FileReader();
reader.onload = function(event) {
var dataURL = this.result;
document.querySelector('img').src = dataURL;
document.querySelector('p').innerHTML = dataURL;
};
var source = reader.readAsDataURL(blob);
}
<img/>
<p></p>
You can't use FileReader to solve this problem, because you are not trying to read local files (that is the purpose of FileReader)
Just convert the image taken from the web link using something like this answer https://stackoverflow.com/a/20285053/912450
I want to load an image from an url into filereader in order to obtain a data url of that image. I tried to search for the solution on google but i can only find solutions to read them from the file input on a local computer.
If you want a usable data-URI representation of the image, then I suggest to load the image in a <img> tag, paint it on a <canvas> then use the .toDataURL() method of the canvas.
Otherwise, you need to use XMLHttpRequest to get the image blob (set the responseType property on the XMLHttpRequest instance and get the blob from the .response property). Then, you can use the FileReader API as usual.
In both cases, the images have to be hosted on the same origin, or CORS must be enabled.
If your server does not support CORS, you can use a proxy that adds CORS headers. In the following example (using the second method), I'm using CORS Anywhere to get CORS headers on any image I want.
var x = new XMLHttpRequest();
x.open('GET', '//cors-anywhere.herokuapp.com/http://www.youtube.com/favicon.ico');
x.responseType = 'blob';
x.onload = function() {
var blob = x.response;
var fr = new FileReader();
fr.onloadend = function() {
var dataUrl = fr.result;
// Paint image, as a proof of concept
var img = document.createElement('img');
img.src = dataUrl;
document.body.appendChild(img);
};
fr.readAsDataURL(blob);
};
x.send();
The previous code can be copy-pasted to the console, and you will see a small image with YouTube's favicon at the bottom of the page. Link to demo: http://jsfiddle.net/4Y7VP/
Alternative download with fetch:
fetch('http://cors-anywhere.herokuapp.com/https://lorempixel.com/640/480/?
60789', {
headers: {},
}).then((response) => {
return response.blob();
}).then((blob) => {
console.log(blob);
var fr = new FileReader();
fr.onloadend = function() {
var dataUrl = fr.result;
// Paint image, as a proof of concept
var img = document.createElement('img');
img.src = dataUrl;
document.body.appendChild(img);
};
fr.readAsDataURL(blob);
}).catch((e) => console.log(e));
I am retrieving a Blob image from a database, and I'd like to be able to view that image using JavaScript. The following code produces a broken image icon on the page:
var image = document.createElement('image');
image.src = 'data:image/bmp;base64,'+Base64.encode(blob);
document.body.appendChild(image);
Here is a jsFiddle containing all the code required, including the blob. The completed code should properly display an image.
You can also get BLOB object directly from XMLHttpRequest. Setting responseType to blob makes the trick. Here is my code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost/image.jpg");
xhr.responseType = "blob";
xhr.onload = response;
xhr.send();
And the response function looks like this:
function response(e) {
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
document.querySelector("#image").src = imageUrl;
}
We just have to make an empty image element in HTML:
<img id="image"/>
If you want to use fetch instead:
var myImage = document.querySelector('img');
fetch('flowers.jpg').then(function(response) {
return response.blob();
}).then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
Source:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
You can convert your string into a Uint8Array to get the raw data. Then create a Blob for that data and pass to URL.createObjectURL(blob) to convert the Blob into a URL that you pass to img.src.
var data = '424D5E070000000000003E00000028000000EF...';
// Convert the string to bytes
var bytes = new Uint8Array(data.length / 2);
for (var i = 0; i < data.length; i += 2) {
bytes[i / 2] = parseInt(data.substring(i, i + 2), /* base = */ 16);
}
// Make a Blob from the bytes
var blob = new Blob([bytes], {type: 'image/bmp'});
// Use createObjectURL to make a URL for the blob
var image = new Image();
image.src = URL.createObjectURL(blob);
document.body.appendChild(image);
You can try the complete example at: http://jsfiddle.net/nj82y73d/
In your example, you should createElement('img').
In your link, base64blob != Base64.encode(blob).
This works, as long as your data is valid http://jsfiddle.net/SXFwP/ (I didn't have any BMP images so I had to use PNG).
I guess you had an error in the inline code of your image.
Try this :
var image = document.createElement('img');
image.src="data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==";
image.width=100;
image.height=100;
image.alt="here should be some image";
document.body.appendChild(image);
Helpful link :http://dean.edwards.name/my/base64-ie.html
In the fiddle your blob isn't a blob, it's a string representation of hexadecimal data.
Try this on a blob and your done
var image = document.createElement('img');
let reader=new FileReader()
reader.addEventListener('loadend',()=>{
let contents=reader.result
image.src = contents
document.body.appendChild(image);
})
if(blob instanceof Blob) reader.readAsDataURL(blob)
readAsDataURL give you a base64 encoded image ready for you image element () source (src)
The problem was that I had hexadecimal data that needed to be converted to binary before being base64encoded.
in PHP:
base64_encode(pack("H*", $subvalue))