Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
resizing an image on the front-end before sending to a server
// Using this code, we can retrieve an image from a user's filesystem, resize the image, and then upload the image
// to a server using AJAX. Because we use base64 encoding, we can just include the image data as just another string value
// in a JSON payload.
// So we can use AJAX to send the file to a server, which is convenient.
// We have one line of relevant html
// get file in the first place => <input type="file" custom-on-change="onAcqImageFileChange" class="form-control">
$scope.onAcqImageFileChange = function (e) {
e.preventDefault();
var file = e.target.files[0];
$scope.acqImageFile = file; // store reference to file
};
function convertToBase64(file, cb) {
var reader = new FileReader();
reader.onload = function (e) {
cb(null, e.target.result)
};
reader.onerror = function (e) {
cb(e);
};
reader.readAsDataURL(file);
}
function resizeImage(base64Str) {
var img = new Image();
img.src = base64Str;
var canvas = document.createElement('canvas');
var MAX_WIDTH = 400;
var MAX_HEIGHT = 350;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
return canvas.toDataURL();
}
$scope.submitImageSelection = function () {
// when the user finally selects the image they want, and clicks submit, we run this fn
var imgFile = $scope.acqImageFile;
convertToBase64(imgFile, function (err, data) {
if (err) {
/// handle error
return;
}
// resize the image like a boss
data = resizeImage(data);
// finally we can send the data to a server as
// just another field in a JSON payload
SomeService.sendDataToServer(data, function(err){
// voila
});
});
};
// note that to display the image selection back to the user before they choose their final selection, you may want to convert to
// base64 each time they change selections.
// to display the image, you can use ng-src:
// <img class="overlay-image" ng-src="{{acqImageData ? acqImageData : '/assets/img/placeholder.png'}}">
// <the end>
@grlsquared

This comment has been minimized.

Copy link

commented Aug 14, 2019

It works fine if you add an "onload" listener on "img" in "resizeImage(base64Str)" function and move the rest part of function inside the onload function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.