Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Create a jpg image from ArrayBuffer data
// Simulate a call to Dropbox or other service that can
// return an image as an ArrayBuffer.
var xhr = new XMLHttpRequest();
// Use JSFiddle logo as a sample image to avoid complicating
// this example with cross-domain issues. "GET", "", true );
// Ask for the result as an ArrayBuffer.
xhr.responseType = "arraybuffer";
xhr.onload = function( e ) {
// Obtain a blob: URL for the image data.
var arrayBufferView = new Uint8Array( this.response );
var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL( blob );
var img = document.querySelector( "#photo" );
img.src = imageUrl;
Copy link

Thank you man

Copy link

ulfgebhardt commented Sep 15, 2018

changed http:// to https:// to avoid chrome problems

Copy link

aidnurs commented Jan 14, 2019

Thanks a lot!

Copy link

Don't forget to call revokeObjectURL() after onload fires to free up the memory used to create the blob URL.

Copy link

Please note this method does not convert a PNG image into a JPG. In order to do so, you have to put the image in a <canvas> and export it using .toDataURI or .toBlob (not always possibile, as the image must have the same origin) using 'image/jpeg' as the output format.

I know this isn't the reason of this gist, just warning other passers-by who may get confused.

Copy link

b3nh commented Jun 21, 2019

Thank you

Copy link

Thank you very much ;)

Copy link

very useful. thank you so much for sharing

Copy link

Thanks a lot, man! You do saved a lot of my life-time ))))

Copy link

ElsaFil commented May 26, 2020

awesome, thanks!

Copy link

i was hoping there was another way to do this...
thanks for your solution, anyways...
but it's exactly what i feared needed to be done...

i feel like i'm being punished for NOT wanting to just throw all my files SEPARATELY on some server >.<

Copy link

spa0807 commented Jun 30, 2020

thanks a lot man

Copy link

khokm commented Dec 4, 2020

You are best!

Copy link

Worked like a charm!

Copy link

ragokan commented Feb 28, 2021

Thanks a lot!

Copy link

Thank you.

Copy link

love you

Copy link

love you

Copy link

Thanks a lot!

Copy link

Thanks a Lot for this, I was wondering about the Int8Array, Uint8Array, Int16Array fetched in the response data object. Is there a difference ?

Copy link

Thanks man. This really saved me. I have a questions. Why does this example use XMLHttpRequest instead of fetch()? I'm assuming that is because the example was written 9 year ago but maybe there is another reason?

Copy link

Thanks for this!

Copy link

khokm commented May 21, 2023

Is wrapping this.response into Uint8Array necessary? Doc says that ArrayBuffer can also be used as blob part.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment