Skip to content

Instantly share code, notes, and snippets.

@geedelur
Last active December 28, 2015 16:59
Show Gist options
  • Save geedelur/7532898 to your computer and use it in GitHub Desktop.
Save geedelur/7532898 to your computer and use it in GitHub Desktop.
callback function for summernote (https://github.com/HackerWins/summernote/) onImageUpload event that resizes the images before sending them to the server
function summernoteOnImageUpload(files, editor, welEditable) {
$.each(files, function(idx, file) {
var max_width = 400;
var max_height = 400;
var reader = new FileReader();
reader.onload = function() {
var tmpImg = new Image();
tmpImg.src = reader.result;
tmpImg.onload = function() {
var tmpW = tmpImg.width;
var tmpH = tmpImg.height;
if (tmpW > tmpH) {
if (tmpW > max_width) {
tmpH *= max_width / tmpW;
tmpW = max_width;
}
} else {
if (tmpH > max_height) {
tmpW *= max_height / tmpH;
tmpH = max_height;
}
}
var canvas = document.createElement('canvas');
canvas.width = tmpW;
canvas.height = tmpH;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0, tmpW, tmpH);
sURL = canvas.toDataURL("image/jpeg");
editor.insertImage(welEditable, sURL);
}
}
reader.readAsDataURL(file);
});
}
/**
*
* usage
* <div id="summernote">Hello Summernote</div>
* $('#summernote').summernote({onImageUpload: summernoteOnImageUpload});
*
**/
@tmaiaroto
Copy link

Note for anyone stumbling upon this. The callback function here does not work for the current version of summernote.js due to an API change. editor.insertImage() will need to be changed. Assuming your editor has been applied to .summernote

$('.summernote').summernote("insertImage", sURL, file.name);

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