Skip to content

Instantly share code, notes, and snippets.

@DaveMBush
Last active July 1, 2017 16:29
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 DaveMBush/0454717c390db1055674ff8a2817f68d to your computer and use it in GitHub Desktop.
Save DaveMBush/0454717c390db1055674ff8a2817f68d to your computer and use it in GitHub Desktop.
Image Blog Post
b64toFile(dataURI): File {
// convert the data URL to a byte string
const byteString = atob(dataURI.split(',')[1]);
// pull out the mime type from the data URL
const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// Convert to byte array
const ab = new ArrayBuffer(byteString.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// Create a blob that looks like a file.
const blob = new Blob([ab], { 'type': mimeString });
blob['lastModifiedDate'] = (new Date()).toISOString();
blob['name'] = 'file';
// Figure out what extension the file should have
switch(blob.type) {
case 'image/jpeg':
blob['name'] += '.jpg';
break;
case 'image/png':
blob['name'] += '.png';
break;
}
// cast to a File
return <File>blob;
}
const canvas = document.createElement("canvas");
context = canvas.getContext('2d');
const base_image = new Image();
base_image.src = 'img/base.png';
base_image.onload = function(){
context.drawImage(base_image, 100, 100);
let dataUrl = canvas.toDataURL('image/jpeg');
}
const image = new Image();
const self = this;
const reader = new FileReader();
reader.onloadend = function () {
reader.onloadend = null;
// make sure the image is loaded before we go
// after width and height;
image.src = null;
image.onload = () => {
image.onload = null;
// do something with the new image here
}
image.src = reader.result;
};
image.onload = () => {
image.onload = null;
const xhr = new XMLHttpRequest();
xhr.onload = function () {
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', image.src);
xhr.responseType = 'blob';
xhr.send();
};
if(action.payload instanceof File) {
// won't be using image.onload so we need to turn it off
image.onload = null;
reader.readAsDataURL(action.payload);
} else {
// this triggers image.onload which triggers reader.readAsDataURL
image.src = action.payload;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment