Thumbnails the easy way

December 14, 2009 | Posted by: Fredrik | Tags: Image Library, ASP.NET, Open source, C#, Snippet

This is the first code sample using the .NET Image Library released under open source license. It covers thumbnail creation, which can be a bit of a hassle some times.

Image Library can handle thumbnail creation in three different ways: cropping, padding and fitting.

To illustrate the different options, here's a couple of samples using a test image of 1024 x 768 pixels in a 256 x 256 pixels thumbnail.

Thumbnail by cropping

This option will ensure that the whole thumbnail area will contain graphics, even if that mean that some of the original image won't be visible.

Thumbnail by padding

This option first fit the whole image inside the dimension provided to the method. Then the thumbnail is padded with the background color to fill out the whole image.

Thumbnail by fitting

This is the more traditional version that you might have come across in the original System.Drawing.Image GetThumbnailImage method.
It ensures that the complete original image is visible within the thumbnail. This may result in a ratio that is different from the dimensions defined in the function call.

Okay, it's time for some coding :)

First of all, get the Image Library here:

.NET Image Library source code at GitHub

or

.NET Image Library package at NuGet

Create your own project and reference the .NET Image Library NuGet-package, dll or project.

The following code will create the three different types of thumbnails (saving them as jpeg in quality 99%).

using Kaliko.ImageLibrary;

namespace TestApp {
public class ThumbnailTests {

public static void TestCreatingThumbnails() {

KalikoImage image = new KalikoImage("garden.jpg");

// Create thumbnail by cropping
KalikoImage thumb = image.Scale(new CropScaling(128, 128));
thumb.SaveJPG("thumbnail-crop.jpg", 99);

// Create thumbnail by fitting
thumb = image.Scale(new FitScaling(128, 128));
thumb.SaveJPG("thumbnail-fit.jpg", 99);

// Create thumbnail by padding. Pad with Color.Wheat
image.BackgroundColor = Color.Wheat;
thumb = image.Scale(new PadScaling(128, 128));
thumb.SaveJPG("thumbnail-pad.jpg", 99);
}
}
}

Comments

comments powered by Disqus