Frage

Since browsers know how to handle JPG files, is there a way to give them the actual binary data of a JPG file dynamically and allowing them to decode it?

I can't supply the file as a normal image.src="path.jpg" because the data is originally a part of another file which is parsed in JS.

In addition, I have weird JPG files that store alpha, and so libraries like https://github.com/notmasteryet/jpgjs can't handle them.

War es hilfreich?

Lösung

You can use Blobs to create objects from binary data that you later pass as an url for image decoding. Assuming you have the binary data stored as typed array you could do something like this:

var blob = new Blob([myTypedArray], {type: 'application/octet-binary'});
var url = URL.createObjectURL(blob);

Now you can pass that url as a source for image:

var img = new Image;
img.onload = function() {
    URL.revokeObjectURL(url);
    ...
};
img.src = url;

Note that you still have make sure that the data you pass in is valid image format that the browser can handle.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top