Creating squared avatar images

In one of my current projects I needed something that takes image uploaded by user and converts it to avatar image. There is requirement for avatar images: they must be 32×32 pixel squares. Here is my solution.

Creating squared thumbnail image from what ever user uploaded is pretty simple process. It is illustrated on image you can see on right side of this posting. Here are some explanations.

  1. Avatar creation processDetect image size
    It doesn’t really matter what dimensions image has. I just wanted to make it visually easier to understand how my algorithm works.
  2. Detect shorter size
    To take a square we have to take one of image sides as square side. We take shorter side to avoid some resizing operations that may affect the quality of avatar image we are creating. We will use Math.Mix to detect correct side length of square.
  3. Focus square to center
    Usually pictures are taken with focus on some object and this object is located it the center area of picture. Today it is not hard to use photo as avatar, so let’s consider this as a default behavior of end user. To get center area we subtract square side length from original imade size and divide the result by two.
  4. Create new image from square
    After steps above we have detected the area of original image we want to use as avatar. Now we will copy this area to new avatar image and save avatar to disc (or database or some other place).

Now you should understand what we are going to do and it’s time to show you my code. I have small and easy method that does all the work mentioned above. I am using classes from System.Drawing and these classes are really powerful. Here is my method.


public void CreateAvatar(int sideLength, Stream fromStream, Stream toStream)
{
   
using (var image = System.Drawing.Image
.FromStream(fromStream))
   
using (var thumbBitmap = new Bitmap
(sideLength, sideLength))
    {
       
var a = Math
.Min(image.Width, image.Height);
       
var
x = (image.Width - a) / 2;
       
var
y = (image.Height - a) / 2;

       
using (var thumbGraph = Graphics
.FromImage(thumbBitmap))
        {
            thumbGraph.CompositingQuality =
CompositingQuality
.HighQuality;
            thumbGraph.SmoothingMode =
SmoothingMode
.HighQuality;
            thumbGraph.InterpolationMode =
InterpolationMode
.HighQualityBicubic;

           
var imgRectangle = new
Rectangle(0, 0, sideLength, sideLength);
            thumbGraph.DrawImage(image, imgRectangle, x, y, a, a,
GraphicsUnit
.Pixel);
            thumbBitmap.Save(toStream,
ImageFormat.Png);
        }
    }
}

If you know some better method how to write this code then please let me know! 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *