Hello fellows,
I am trying to make a crop method for a specific image with a specific coordinates. While searching around the Internet I found some examples. The fastest
I found was this one and I made some fixes along the way. Can someone give me any suggestions to make it more faster?
private static Image CropImage(Image image,int xStart, int yStart, int height, int width)
{
try
{
if (image.Height < height)
{
height = image.Height;
}
if (image.Width < width)
{
width = image.Width;
}
var bmphoto = new Bitmap(width,height, PixelFormat.Format32bppPArgb);
bmphoto.SetResolution(image.VerticalResolution, image.HorizontalResolution);
var grPhoto = Graphics.FromImage(bmphoto);
grPhoto.CompositingMode = CompositingMode.SourceOver;
grPhoto.CompositingQuality = CompositingQuality.HighSpeed;
grPhoto.InterpolationMode = InterpolationMode.Default;
grPhoto.PixelOffsetMode = PixelOffsetMode.Half;
grPhoto.SmoothingMode = SmoothingMode.None;
grPhoto.DrawImage(image, new Rectangle(0, 0, width, height),xStart,yStart,width,height,GraphicsUnit.Pixel);
var mm = new MemoryStream();
bmphoto.Save(mm, ImageFormat.Jpeg);
image.Dispose();
bmphoto.Dispose();
grPhoto.Dispose();
var outimage = Image.FromStream(mm);
return outimage;
}
catch (Exception ex)
{
throw new Exception("Error cropping image, the error was: " + ex.Message);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var stopwatch = new Stopwatch();
var imagePath = @"11069.jpg";
var resultImagePath = @" Woman Croped.jpg";
stopwatch.Start();
var resultImage = CropImage(new Bitmap(imagePath), 640,480,2400,1500); // ~177 ms
resultImage.Save(resultImagePath);
resultImage.Dispose();
stopwatch.Stop();
MessageBox.Show(stopwatch.Elapsed.Milliseconds + "ms");
}Is there anything more to do with the CropImage() method to increase the performance?