Skip to content

Instantly share code, notes, and snippets.

@MIchaelMainer
Created January 4, 2016 21:49
Show Gist options
  • Save MIchaelMainer/ef5202f5566987636eda to your computer and use it in GitHub Desktop.
Save MIchaelMainer/ef5202f5566987636eda to your computer and use it in GitHub Desktop.
WordJS doesn't return MIME type for images. I need to detect that for inserting images into the HTML canvas.Here are some links and code I started to work on when researching how to do this.
// http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript, thank you Jeremy Banks
function createBlob(base64EncodedImage) {
var myString = base64EncodedImage.value.slice(0);
// This goes into the WordJS library.
var byteCharacters = window.atob(myString);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
// THIS IS WHER I HAVE AN ISSUE.
var blob = new Blob(byteArray);
// http://stackoverflow.com/questions/18299806/how-to-check-file-mime-type-with-javascript-before-upload, thank you Drakes
var fileReader = new FileReader();
var header = "";
fileReader.onloadend = function (e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
for (var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
console.log(header);
// Check the file signature against known types
};
fileReader.readAsArrayBuffer(blob);
switch (header) {
case "89504e47":
type = "image/png";
break;
case "47494638":
type = "image/gif";
break;
case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
type = "image/jpeg";
break;
default:
type = "unknown"; // Or you can use the blob.type as fallback
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment