Steven
Steven

Reputation: 18859

Create a thumbnail from only part of an image

I'm creating a thumbnail right now like this:

// create thumbnail and save
var image = Image.FromFile(Server.MapPath(imageFilename));
var thumb = image.GetThumbnailImage(image.Width / 10, image.Height / 10, () => false, IntPtr.Zero);
thumb.Save(Server.MapPath(Path.ChangeExtension(imageFilename, "thumb" + Path.GetExtension(imageFilename))));

All it does is take the image, create a thumbnail 1/10th of the size, and save it.

I'd like to be able to create a thumbnail out of only part of the image. So say I have an image that is 200px by 200px. How can I take a 100px by 100px crop out of the middle of the image, and create a thumbnail out of it?

Upvotes: 0

Views: 187

Answers (1)

Adam Tuliper
Adam Tuliper

Reputation: 30152

Check out the code here for cropping an image:

https://web.archive.org/web/20141006051530/http://bobpowell.net/changing_resolution.aspx


using(Bitmap bitMap = (Bitmap)Image.FromFile("myimage.jpg")) // assumes a 400 * 300 image from which a 160 * 120 chunk will be taken
{

using(Bitmap cropped = new Bitmap(160,120))
{

  using(Graphics g=Graphics.FromImage(cropped))
  {

    g.DrawImage(bitMap, new Rectangle(0,0,cropped.Width,cropped.Height),100,50,cropped.Width,cropped.Height,GraphicsUnit.Pixel);


    cropped.Save("croppedimage.jpg",ImageFormat.Jpeg);
  }
}
}

Upvotes: 3

Related Questions