3

I want to cut the the specific portion of the the picture and use it to compare the cropped image with another stored in the HDD. The problem is that I don't know how to get a specific section of the source image. I know the location (X,Y) of the image to be cropped.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
Farid-ur-Rahman
  • 1,809
  • 9
  • 31
  • 47
  • Beware - this is possible but inefficient. I once slowed an ASP.NET app to a crawl by doing this. I ended up creating a `BitmapRegion` class that delegated most methods to the original bitmap but shared the pixel data. – finnw Jan 30 '11 at 21:29
  • Yeah, something like that is a good idea if you find this to be a bottleneck in your application. My example copies the image. – Ed S. Jan 30 '11 at 21:34

2 Answers2

18

This will load the original and create a cropped version starting at (0,0) and with dimensions of 64x64.

Bitmap original = new Bitmap( @"C:\SomePath" );
Rectangle srcRect = new Rectangle( 0, 0, 64, 64 );
Bitmap cropped = (Bitmap)original.Clone( srcRect, original.PixelFormat );

BTW, you don't specify if this is WinForms or WPF, so going with WinForms as I don't really know WPF image manipulation functions.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • 9
    @user574917: Your caps lock key is stuck. – Cody Gray - on strike Jan 30 '11 at 11:50
  • It shows an error: Error 1 Cannot implicitly convert type 'System.Drawing.Image' to 'System.Drawing.Bitmap'. An explicit conversion exists (are you missing a cast?) – Farid-ur-Rahman Jan 30 '11 at 12:18
  • Sorry, you need to cast the return value of Bitmap.FromFile because that method comes from the Image class. I changed it to just use the constructor instead, it was late :) – Ed S. Jan 30 '11 at 20:27
2

For those who need to use the cropped image for their website within img-tag , you need some more code (just advicing, because i needed it myself) Take the code above plus this:

 byte[] imgbytes;    
 using (MemoryStream stream = new MemoryStream())
 {
        cropped.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        imgbytes = stream.ToArray();
 }
 <img src="@String.Format("data:image/png;base64,{0}", Convert.ToBase64String(imgbytes))" />
blu3drag0n
  • 61
  • 4