JavaScript - rotate jpeg image / picture to correct orientation before sending to server
In this article, we would like to show how to correct orientation for JPG / JPEG image before sending to the server using JavaScript (in a web browser).
The problem occurs when we have devices that have built-in orientation sensors and pictures are made in different phone positions. Some software on devices does not correct it automatically when we send it via web browser and is necessary to do it somehow - we need to know on what devices correction is needed!
By default orientation for JPEG is placed inside Exif Metadata that is attached to the picture file. There are some libraries that let us to read that information and rotate pictures by self, but it can be difficult because rotation is necessary only on some devices and we need to know when rotation is needed.
There is some trick that solves the problem in an easy way:
- drawing image on canvas,
- saving it back,
- sending image to the server.
It works because the HMTL img
element has built-in rotation support before displaying it.
So you can use it with canvas
and extract corrected image data to send it.
The approach works in all browsers and we can set high quality for our pictures before extracting them back from canvas.
Example code:
xxxxxxxxxx
<html>
<body>
<input id="picture" type="file" />
<button id="sender">Send corrected picture</button>
<script>
function loadImage(file, callback) {
var image = document.createElement('img');
image.onload = function() {
URL.revokeObjectURL(image.src);
callback(image);
};
image.onerror = function() {
URL.revokeObjectURL(image.src);
console.log('Incorrect image format.');
};
image.src = URL.createObjectURL(file);
}
function correctImage(file, callback) {
loadImage(file, function(image) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0, image.width, image.height);
try {
var correctedData = canvas.toDataURL('image/jpeg', 1.0);
callback(correctedData);
} catch (e) {
console.log('Save image error.');
}
});
}
var picture = document.querySelector("#picture");
var sender = document.querySelector("#sender");
// picture saved as data url with base64 encoding
var correctedData = null;
picture.addEventListener('change', function() {
if (this.files && this.files.length > 0) {
var file = this.files[0];
if (file.type == 'image/jpeg' // only in this case rotation is needed
|| file.type == 'image/bmp'
|| file.type == 'image/gif'
|| file.type == 'image/png'
|| file.type == 'image/tiff') {
correctImage(file, function(data) {
correctedData = data;
});
} else {
console.log('Incorrect image format.');
}
}
});
sender.addEventListener('click', function() {
if (correctedData) {
//TODO: correctedData sending
console.log(correctedData.substring(0, 50) + '...');
}
});
</script>
</body>
</html>
Note: check this article if URL object is not supported.