Skip to content

Instantly share code, notes, and snippets.

Embed
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.
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();
@yashwanth2804

This comment has been minimized.

Copy link

yashwanth2804 commented Jul 19, 2018

Thank you man

@ulfgebhardt

This comment has been minimized.

Copy link

ulfgebhardt commented Sep 15, 2018

https://jsfiddle.net/b8d9032s/2/

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

@aidnurs

This comment has been minimized.

Copy link

aidnurs commented Jan 14, 2019

Thanks a lot!

@jhuckaby

This comment has been minimized.

Copy link

jhuckaby commented Jan 30, 2019

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

@MaxArt2501

This comment has been minimized.

Copy link

MaxArt2501 commented Jun 9, 2019

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.

@arklabco

This comment has been minimized.

Copy link

arklabco commented Jun 21, 2019

Thank you

@dalalRohit

This comment has been minimized.

Copy link

dalalRohit commented Jun 30, 2019

Thank you very much ;)

@naveedahmed986

This comment has been minimized.

Copy link

naveedahmed986 commented Aug 7, 2019

very useful. thank you so much for sharing

@edilovaysky

This comment has been minimized.

Copy link

edilovaysky commented Sep 24, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.