I have the following code to work with images from a stream. My intention is to pick a subregion of it and resize it to 100x100. I do not know the format of the image beforehand.
var image = new Bitmap(stream);
var destArea = new Rectangle(0, 0, 100, 100);
var srcArea = new Rectangle(x, y, width, height);
var gfx = Graphics.FromImage(image);
gfx.DrawImage(image, destArea, srcArea, GraphicsUnit.Pixel);
var ms = new MemoryStream();
image.Save(ms, image.RawFormat);
For some reason, this is taking the subregion I want, resizing it and putting it on top of the original image, so that the result is a mixture of the original and my desired result.
I have been through several guides, posts on image processing but I still don't know for sure where am I wrong. Would you mind to help me out?
Also, I would really appreciate if you also explained to me what is it that I'm missing (a little bit of theory behind the code).
Thanks!
If you're resizing an image, you'll need a new image object into which you'll put your resized image. What you're missing is the creation of the new 100x100 image. Here's how your code should look:
var image = new Bitmap(stream);
var destArea = new Rectangle(0, 0, 100, 100);
var srcArea = new Rectangle(x, y, width, height);
// Destination image
var destImage = new Bitmap(destArea.Width, destArea.Height);
var gfx = Graphics.FromImage(destImage);
gfx.DrawImage(image, destArea, srcArea, GraphicsUnit.Pixel);
var ms = new MemoryStream();
destImage.Save(ms, image.RawFormat);
I would also recommend wrapping all the GDI+ objects in using
statements, as they generally don't play well with garbage collection.