Skip to content

Instantly share code, notes, and snippets.

@kirbysayshi
Created August 20, 2014 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kirbysayshi/86751ac1e26ab7f2cba6 to your computer and use it in GitHub Desktop.
Save kirbysayshi/86751ac1e26ab7f2cba6 to your computer and use it in GitHub Desktop.
image "type" juggling
function imageToCanvas(image, opt_cvs, cb) {
if (!cb) { cb = opt_cvs; }
var cvs = opt_cvs || document.createElement('canvas');
var ctx = cvs.getContext('2d');
cvs.width = image.width;
cvs.height = image.height;
ctx.drawImage(image, 0, 0);
cb(null, cvs);
}
function imageToArrayBuffer(image, cb) {
var reader = new FileReader();
reader.onload = function() {
cb(reader.error, reader.result);
}
imageToCanvas(image, function(err, cvs) {
cvs.toBlob(reader.readAsArrayBuffer.bind(reader))
})
}
function imageDataToImage(imageData, opt_image, cb) {
if (!cb) { cb = opt_image; }
var img = opt_image || document.createElement('img');
var cvs = document.createElement('canvas');
var ctx = cvs.getContext('2d');
cvs.width = imageData.width;
cvs.height = imageData.height;
ctx.putImageData(imageData, 0, 0);
canvasToImage(cvs, img, cb);
}
function fileToImage(file, opt_image, cb) {
if (!cb) { cb = opt_image; }
var img = opt_image || document.createElement('img');
var url = URL.createObjectURL(file);
img.onload = function() {
URL.revokeObjectURL(url);
cb(null, img);
}
img.src = url;
}
function canvasToImage(canvas, opt_image, cb) {
if (!cb) { cb = opt_image; }
var url;
var img = opt_image || document.createElement('img');
img.onload = function() {
URL.revokeObjectURL(url);
cb(null, img);
}
canvas.toBlob(function(blob) {
url = URL.createObjectURL(blob);
img.src = url;
});
}
function blobToImage(blob, opt_image, cb) {
if (!cb) { cb = opt_image; }
var img = opt_image || document.createElement('img');
var url = URL.createObjectURL(blob);
img.onload = function() {
URL.revokeObjectURL(url);
cb(null, img);
}
img.src = url;
}
exports.imageToCanvas = imageToCanvas;
exports.imageToArrayBuffer = imageToArrayBuffer;
exports.imageDataToImage = imageDataToImage;
exports.fileToImage = fileToImage;
exports.canvasToImage = canvasToImage;
exports.blobToImage = blobToImage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment