Skip to content

Instantly share code, notes, and snippets.

@Qqwy
Created February 18, 2016 23:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Qqwy/7d3022c3a622f5361eba to your computer and use it in GitHub Desktop.
Save Qqwy/7d3022c3a622f5361eba to your computer and use it in GitHub Desktop.
function base64ImageUploader(dialog) {
var reader, image_url, img;
var canvas = document.createElement("canvas");
var canvas_context = canvas.getContext('2d');
function rotateImage(direction){
//These are swapped when rotating
canvas.width = img.height;
canvas.height = img.width;
canvas_context.rotate(direction*Math.PI/2)
if(direction > 0){
canvas_context.translate(0,-canvas.height);
}else{
canvas_context.translate(-canvas.width,0);
}
canvas_context.drawImage(img, 0, 0);
setImageFromDataURL(canvas.toDataURL("image/png"), img.alt)
}
function setImageFromDataURL(data_url, file_name){
image_url = data_url
img = new Image();
img.src = image_url
img.alt = file_name
dialog.populate(image_url, [img.width,img.height]);
}
function cropImage(crop_region){
canvas.width = img.width*crop_region[2];
canvas.height = img.height*crop_region[3];
canvas_context.translate(-img.width*crop_region[0], -img.height*crop_region[1]);
canvas_context.drawImage(img, 0, 0);
setImageFromDataURL(canvas.toDataURL("image/png"), img.alt);
}
dialog.bind('imageUploader.cancelUpload', function () {
});
dialog.bind('imageUploader.clear', function () {
// Clear the current image
dialog.clear();
img = null;
});
dialog.bind('imageUploader.fileReady', function (file) {
var reader = new FileReader();
if (file){
reader.readAsDataURL(file);
reader.addEventListener('load', function(){
setImageFromDataURL(reader.result, file.name)
});
}
});
dialog.bind('imageUploader.rotateCCW', function () {
rotateImage(-1);
});
dialog.bind('imageUploader.rotateCW', function () {
rotateImage(1);
});
dialog.bind('imageUploader.save', function () {
if (dialog.cropRegion()) {
cropImage(dialog.cropRegion());
}
dialog.save(
image_url,
[img.width, img.height],
{
'alt': img.alt,
'data-ce-max-width': img.width
}
);
});
}
ContentTools.IMAGE_UPLOADER = base64ImageUploader;
@CapRoberts
Copy link

Looks nice but how to you incorporate this into content tools?

@d0brii
Copy link

d0brii commented Aug 18, 2016

It's not working
Uncaught TypeError: dialog.bind is not a function
dialog.bind('imageUploader.cancelUpload', function () {...

New event system (based on native DOM event system), this will see bind, unbind and trigger methods against UI components replaced with addEventListener, dispatchEvent, removeEventListener (potentially breaking existing code).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment