Image scaling and rotating in C/C++

kafuchau picture kafuchau · Nov 18, 2008 · Viewed 71.9k times · Source

What is the best way to scale a 2D image array? For instance, suppose I have an image of 1024 x 2048 bytes, with each byte being a pixel. Each pixel is a grayscale level from 0 to 255. I would like to be able to scale this image by an arbitrary factor and get a new image. So, if I scale the image by a factor of 0.68, I should get a new image of size 0.68*1024 x 0.68*2048. some pixels will be collapsed onto each other. And, if I scale by a factor of say 3.15, I would get a larger image with pixels being duplicated. So, what's the best way to accomplish this?

Next, I would like to be able to rotate an image by an arbitrary angle, in the range of 0 to 360 degrees (0 - 2Pi). Cropping of the image after rotating isn't an issue. What would be the best way to do this?

Answer

Skizz picture Skizz · Nov 18, 2008

There are many ways to scale and rotate images. The simplest way to scale is:

dest[dx,dy] = src[dx*src_width/dest_width,dy*src_height/dest_height]

but this produces blocky effects when increasing the size and loss of detail when reducing the size. There are ways to produce better looking results, for example, bilinear filtering.

For rotating, the src pixel location can be calculated using a rotation matrix:

sx,sy = M(dx,dy)

where M is a matrix that maps destination pixels to the source image. Again, you'll need to do interpolation to produce non-blocky results.

But there are plenty of libraries available if you don't want to get into the mathematics of image processing.