Skip to content

Instantly share code, notes, and snippets.

@candycode
Created March 7, 2014 15:24
Show Gist options
  • Save candycode/f18ae1767b2b0aba568e to your computer and use it in GitHub Desktop.
Save candycode/f18ae1767b2b0aba568e to your computer and use it in GitHub Desktop.
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.
xhr.open( "GET", "http://fiddle.jshell.net/img/logo.png", 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;
};
xhr.send();
@spa0807
Copy link

spa0807 commented Jun 30, 2020

thanks a lot man

@khokm
Copy link

khokm commented Dec 4, 2020

You are best!

@kevin700brands
Copy link

Worked like a charm!

@ragokan
Copy link

ragokan commented Feb 28, 2021

Thanks a lot!

@haritaAi
Copy link

Thank you.

@rachtibat
Copy link

love you

@Er-shams
Copy link

love you

@endvvell
Copy link

Thanks a lot!

@mza-codes
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 ?

@alamilladev
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?

@fivestones
Copy link

Thanks for this!

@khokm
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.

@shyamjayakannan
Copy link

Thanks a lot for this

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