Reputation: 856
I know that I can use FileReader
or URL.createObjectURL
to parse Blob
into a string and set the image.src
with it.
But I want to know if I can set Image content directly with a Blob
?.
Upvotes: 2
Views: 2535
Reputation: 136678
Use a blobURL that you do create using URL.createObejctURL(blob);
.
In comments you state that you have concerns about browser support and memory usage (you even talk about memory leak...).
Only a few versions of Chrome did support the FileReader object while not supporting URL.createObjectURL (IIRC that was around v14). Internet Explorer added support in IE10, just like they did for the Blob object and FileReader.
A blobURL is just a pointer to data that is either already in memory, or only on disk. A pointer has like no weight in memory.
A dataURL on the other hand is a string representation of binary data. It weights around 34% more than the data it represents (because binary needs to be mapped to more safe-characters).
Now, to paint the image that is at the other end of the URIs,
Not only this, but if you are going to assign this dataURI in multiple places, then it's 1.34x more data every time you simply copy the string, and given the how hard it is to cache a dataURI, you end up using a lot of memory to represent the same binary data...
Memory leaks?
No. There is no memory leaks. It is simply that when a Blob gets referenced by a blobURL, then this Blob can't be collected by the GarbageCollector, for as long as the blobURL has not been revoked. But given that blobURLs life-time is tied to the Document that did create it, it will die anyway at next refresh.
Also, if you are dealing with data that come from the user's disk, then the blobURL is really just a pointer and no data is stored in memory.
There are really only a few use cases for the readAsDataURL
method of the FileReader, and unless you are sure you must use it, then just use a blobURL.
Upvotes: 6
Reputation: 21
You cannot directly set image.src
with a Blob
. The image.src
needs you to provide an url which is based on an http link, base64 data or virtual blob url address. Blob
is a binary object and doesn't belong to any kind of above options. As you say Blob
needs URL.createObjectURL
to convert it to a virtual blob url address that can be recognized by image.src
.
Upvotes: 2