Skip to content

Instantly share code, notes, and snippets.

@ruanyl
Forked from candycode/image-arraybuffer.js
Created January 31, 2018 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruanyl/6bb0ff091dfa6d1cefbe20a4e075f196 to your computer and use it in GitHub Desktop.
Save ruanyl/6bb0ff091dfa6d1cefbe20a4e075f196 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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment