The title of this post might make it sound fancier than it is. The question here is about loading up a custom image format without depending on some codec having been installed system-wide (which a Windows Store app can’t do anyway). It also answers the question about just getting to the bits of an image file generally.

The trick is to read the file contents into a buffer, and then read the bytes out of the buffer. For example, here’s a roundabout way to load a JPEG:

var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.fileTypeFilter.replaceAll([‘.jpg’, ‘.jpeg’]);

picker.pickSingleFileAsync().then(function (file) {
return Windows.Storage.FileIO.readBufferAsync(file);
}).done(function (buffer) {
var reader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
var bytes = new Uint8Array(buffer.length);
var blob = new Blob([bytes], { type: ‘image/jpeg’ });

    var img = document.createElement(‘img’);
img.src = URL.createObjectURL(blob);

This is highly redundant for built-in formats, of course, because you can just take the StorageFile (in file) from pickSingleFileAsync and pass it direcly tro URL.createObjectURL at the last line of this snippet. (Better yet, if you don’t need the full image, use the StorageFile.getThumbnailAsync or getScaledImageAsThumbnailAsync to minimize overhead.)

For some other format that lacks built-in support, however, this snippet shows you how to load up the bits into the bytes variable, at which point you can do whatever you want with it. To display a custom image format, you’ll need to translate it into bits of a supported file type. If you converted bytes into an array of jpegBytes, then you could just pass the latter to new Blob and everything else is the same. (You could also write the jpegBytes to a new StorageFile and then display it like you would any other, if you want to preserve the conversion.)

Thanks to Luke Hoban for this snippet.

Comments are closed