avr. 18

If you need to create a thumbnial on the fly of a given image, it is quite easy to do in C# as the Image object include a GetThumbnailImage method.

using ( Image originalImage = Image.FromFile(@"c:\temp\originalimage.jpg") )
{
   int newWidth = originalImage.Width / 2;
   int newHeight = originalImage.Height / 2;
   Image resizedImage = originalImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
   resizedImage.Save(@"c:\temp\resizedimage.jpg");
}

This method works fine, but may in some cases produce images of bad quality, spacially when dealing with GIF or PNG with transparency. Indeed, it will generate a Black background behind the image. You could correct this problem by handling the resize manually : 

using ( Image originalImage = Image.FromFile(@"c:\temp\originalimage.jpg") )
{
   int newWidth = originalImage.Width / 2;
   int newHeight = originalImage.Height / 2;

   Image resizedImage = new Bitmap(newWidth, newHeight);
   using ( Graphics g = Graphics.FromImage(resizedImage) )
   {
      g.InterpolationMode = InterpolationMode.HighQualityBicubic;
      g.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight);
      g.DrawImage(originalImage, 0, 0, newWidth, newHeight);
   }
   resizedImage.Save(@"c:\temp\resizedimage.jpg");
}

The resulting image will be a bit bigger (size in octet) but will handle correctly any type of image.

Commentaires

Fabian Vilers

Posted on lundi, 18 avril 2011 14:56

Interesting, I was doing something similar but without using a Graphic object (thus, without specifying the InterpolationMode).

Ajouter un commentaire




biuquote
  • Commentaire
  • Aperçu immédiat
Loading