Resize and Rotate Images Using JavaScript

Uploadcare
7 min readJul 14, 2021

--

If you are a Web Developer, you may be wondering how you could resize and rotate images. Well, if you are using JavaScript, you are in luck! Resizing and rotating images is entirely possible using JavaScript. Let’s get into it (by the way, this post assumes you have a basic understanding of coding and web development)!

Resizing Images using JavaScript

The way we’re going to resize an image in our case is going to require HTML, CSS, and JavaScript as follows:

<img id="container" src="Your image here"/>
<button>Resize</button>
#container {
width: 300px;
height: 300px;
border: 1px solid;
}
document.querySelector('button').onClick = function() {
const image = document.getElementById('container');
image.style.width = '450px';
image.style.height = 'auto';
}

On your page you should see a Resize button which, when clicked, will resize the photo to 450px from 300px. You can easily change the pixel count under image.style.width to whatever you’d like.

Automated Image Resizing

Before we continue, I am going to briefly go over the concept of automatically resizing images when you upload them to a server. Since image file sizes can get very large, this is quite a handy thing to do if you have a large website or app, and you need to manage resources. To do this automated image resizing we are going to use the File Reader API (which you can learn more about here https://developer.mozilla.org/en-US/docs/Web/API/FileReader) and the Canvas API (https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API). We are going to use File Reader to choose an image file from our computer. The HTML code would be as follows:

<input type="file" id="myuploader">
<button onClick='resize()'>Resize</button>
<img id="image">

Next on to the JavaScript:

function resize(){

const resize_width = 600;

const item = document.querySelector('#myuploader').files[0];

const reader = new FileReader();

reader.readAsDataURL(item);
reader.name = item.name;
reader.size = item.size;
reader.onload = function(event) {
const img = new Image();
img.src = event.target.result;
img.name = event.target.name;
img.size = event.target.size;
img.onload = function(el) {
const elem = document.createElement('canvas');

const scaleResize = resize_width / el.target.width;
elem.width = resize_width;
elem.height = el.target.height * scaleResize;

const ctx = elem.getContext('2d');
ctx.drawImage(el.target, 0, 0, elem.width, elem.height);

const srcEncoded = ctx.canvas.toDataURL('image/jpeg', 1);

document.querySelector('#image').src = srcEncoded;

}
}
}

If you work through the code, we are setting the image width to 600. We are setting up the File Reader, and getting the data from the image file (the data is being converted into base64 format). We then create a canvas element and scale it with some simple math. Notice the drawImage, which is a specific Canvas method – drawImage “draws” the image thumbnail onto the canvas for us. The data is then encoded. From here one could send off the encoded base64 data to a server, but that is beyond the scope of this post.

Image Resizing with Uploadcare

Uploadcare supports easy image transformations on the fly. Check out our Transformations Documentation. If you don’t already have an account with Uploadcare, you can start with a free account, and get started using Uploadcare’s Quick Start documentation which you can find here https://uploadcare.com/docs/start/quickstart/.

Let’s take a quick look at how image resize operations would work in Uploadcare. Once you log in to the Dashboard, go to Files; here we can upload an image to Uploadcare.

I’m going to use a cute photo of a puppy that I grabbed for free from Unsplash. Drag an image file to the area indicated on the page. Once the file is uploaded you should see something like this:

Click on the file, and you’ll be taken to the File info screen. As you scroll down you will be able to see some examples of the on the fly image transformations that you can do, on request, with Uploadcare. Since Uploadcare receives requests to transform images via a UUID (an Uploadcare CDN URL), we can take a look at some examples of how one would transform images using Uploadcare via a few UUIDs. It is important to note that when we transform images using Uploadcare, the original image file doesn’t change.

We could rescale an image keeping its original proportions with:

//:uuid/-/preview/400x400/

We can resize the photo to 200×200 with:

//:uuid/-/resize/200x200/

Lets try Uploadcare’s smart crop function:

//:uuid/-/scale_crop/400x800/smart/

Uploadcare also has a smart resize function, an example of this would be:

//:uuid/-/smart_resize/440x600

Zoom In and Out of Images using JavaScript

To zoom in and out of images using JavaScript, we are going to return to our friend the Canvas API which we discussed earlier, in particular, we are using the Canvas scale method. The important thing to notice in the HTML is matching the canvas id with the document.GetElementByID, as well as the width and height settings. What we are doing is creating the canvas element, clearing the canvas, then we are telling the canvas to draw the image. We attach Event Listeners to click functions which tell the Canvas API how much to zoom in and zoom out, by attaching the click functions to the myDraw function.

<div id="wrapper">
<canvas id="myCanvas" width="600" height="600">
</canvas>
<div id="buttonWrapper">
<input type="button" id="plus" value="+"><input type="button" id="minus" value="-">
</div>
</div>
function myDraw(scale){
const canvas = document.getElementById("myCanvas");
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.scale(scale, scale);
context.drawImage(image, 0 , 0 , canvas.width, canvas.height);
}

window.onload = function(){
canvas = document.getElementById("myCanvas");

image = new Image();
image.src = 'Your image here';

document.getElementById("plus").addEventListener("click", function(){
myDraw(1.2);
}, false);

document.getElementById("minus").addEventListener("click", function(){
myDraw(0.8);
}, false);

image.onload = function () {
myDraw(1.0);
}
};

You may have noticed, we are essentially scaling an image with Canvas to get the zoom feature. If we just wanted to simply scale an image using Canvas we could do something like this:

<body onload="drawCanvas();">
<div>
<canvas id="myCanvas" width="350" height="350"></canvas>
</div>
</body>
let canvas;
let img;
let x = 50;
let y = 50;

let scale = 0;
let scaleDirection = 0.2;

function drawCanvas() {
canvas = document.getElementById("myCanvas");

if (canvas.getContext) {

img = new Image();
img.onload = loadingComplete;
img.src = "Your Image";
}
}

function loadingComplete(e) {
setInterval(loop, 25);
}

function loop() {
let canvasContext = canvas.getContext('2d');

canvasContext.fillStyle = "rgb(255,255,255)";
canvasContext.fillRect(0, 0, canvas.width, canvas.height);
canvasContext.save();
canvasContext.translate(x + img.width * 0.5, y + img.height * 0.5);
canvasContext.scale(scale, scale);
canvasContext.translate(-img.width * 0.5, -img.height * 0.5);
canvasContext.drawImage(img, 0, 0);
canvasContext.restore();

scale += scaleDirection;
if (scale < 0.2 || scale > 2) {
scaleDirection = -scaleDirection;
}
}

The above example uses a loop function and animates our image, scaling it in and out, just to show what you can do with image scaling in a fun way. We could, of course, use buttons to scale instead of an animation. Scaling an image is simply resizing an image. Image software packages use algorithms to assist with scaling images, you can learn more about image scaling here https://www.easytechjunkie.com/what-is-image-scaling.htm

To zoom an image in Uploadcare you would use crop and then scale the image. An example of how to do this would be the following:

<input type="hidden" role="uploadcare-uploader" name="my_file"
data-crop="400x300 upscale"
/>

Let’s move on to rotating images.

Rotate Images with JavaScript

Rotating images using HTML, CSS, and JavaScript is pretty simple. We can turn, or rotate images using the following code. The image will turn 90 degrees in response to an onClick event:

<img id="turn" onClick="turn(this)" src="Your image here"/>#turn {
transition: all 0.9s ease;
border: 0.0625em solid red;
border-radius: 3.75em;
}
let turnAngle = 90;function turn(image) {
image.setAttribute("style", "transform: rotate(" + turnAngle + "deg)");
turnAngle = turnAngle + 90;
}

In addition to the JavaScript logic, the above example relies on the CSS transform property. If you wanted to turn the image upside down, and then rightside up by clicking on it, you can easily modify the code to be 180 degrees instead of 90. You can also customize how fast the image turns by changing the transition property: i.e. if you want it to turn faster you can set it to a lower number for easing.

Rotating Images with Uploadcare

Rotating images with Uploadcare is a simple affair, as we see with our puppy example. This is how you would manually rotate the image 90 degrees.

//:uuid/-/rotate/90/

You can also choose autorotation as an option!

//:uuid-/autorotate/yes/

Flipping Images

We can use the following code to flip an image horizontally, using a cool mouseover effect!

<div id="flip" onmouseover="flip()"><img src="Your Image Here"></div>#flip {
display: block;
width: 50px;
height: 50px;
padding: 25px;
color: white;
font-family: 'Arial', sans-serif;
}
let k = 0;
function flip() {
let j = document.getElementById("flip");
k += 180;
j.style.transform = "rotatey(" + k + "deg)";
j.style.transitionDuration = "0.5s"
}

Flipping images with Uploadcare is as simple as using this command.

//:uuid-/flip/

Conclusion

We can see how Uploadcare makes it easier to transform images compared to JavaScript. Image files are hosted on Uploadcare and delivered through Uploadcare’s CDN network. Rather than dealing with potentially complex JavaScript programming, one can easily manipulate images in Uploadcare with requests issued in the image URLs. Uploadcare can also resize images with higher quality

And that’s it — congratulations! You’ve learned the basics of image manipulation and transformations with JavaScript and Uploadcare. Give yourself a pat on the back, you’ve earned it!

Written by Maurice Fawcett

--

--

Uploadcare

Uploadcare is file management platform and a CDN for user-generated content.