I don't know how about you, but for me visiting The Code Projects at least once a day have become a pleasant and necessary habit. It's really a valuable web site with a wealth of useful samples and projects for .NET. So, the other day I've stumbled upon this article on the web site. It explains how to create thumbnail images from a directory of Adobe Acrobat PDF documents. The author gives details on a technique of using a template image for a thumbnail, making it transparent and overlaying it on a top of resized original image. The code in the article is using available in .NET GDI+ methods like Image.GetThumbnailImage, Bitmap.MakeTransparent, etc… So I asked myself a question: “Is it still possible to implement a similar technique in Compact Framework?” Aside from saving the resulting image to a file I couldn’t see any problems in doing that and in 15 minutes I had this code…
The simplified implementation of the GetThumbnailImage goes first:
public static Bitmap GetThumbnailImage(Bitmap image, int height, int width)
{
Bitmap bmp = new Bitmap(height, width);
//create temp Graphics
Graphics gx = Graphics.FromImage(bmp);
//Resize the image
gx.DrawImage(image, new Rectangle(0, 0, height, width), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
//don't forget the dispose
gx.Dispose();
return bmp;
}
Now the CF version of the code from the article:
int thumbnailWidth = 38;
int thumbnailHeight = 52;
//Load original bitmap first
Bitmap orig = new Bitmap(@"\Program Files\ThumbnailProj\today.PNG");
//Create a thumbnailed version
Bitmap thumbOrig = GetThumbnailImage(orig, thumbnailWidth, thumbnailHeight);
//Load a template image
Bitmap thumbTemp = new Bitmap(@"\Program iles\ThumbnailProj\template_portrait.gif");
//Create new blank bitmap
Bitmap thumbnailBitmap = new Bitmap(thumbnailWidth + 7, thumbnailHeight + 7);
Graphics gx = Graphics.FromImage(thumbnailBitmap);
gx.Clear(Color.White);
//Draw a thumbnailed image version first
gx.DrawImage(thumbOrig, 2, 2);
//Draw a template image on the top with transparent attributes.
//This is what we do instead of Bitmap.MakeTransparent()
ImageAttributes attr = new ImageAttributes();
attr.SetColorKey(thumbTemp.GetPixel(5, 5), thumbTemp.GetPixel(5, 5));
gx.DrawImage(thumbTemp, new Rectangle(0, 0, thumbTemp.Width, thumbTemp.Height), 0, 0, thumbTemp.Width, thumbTemp.Height, GraphicsUnit.Pixel, attr);
//Draw the final image on the Form/Control
Graphics gxScr = this.CreateGraphics();
gxScr.DrawImage(thumbnailBitmap, 10, 10);
You can download the whole
demo project here.