2012年5月9日 星期三

Very simple image re-sizing in C#

Today I did some research on re-sizing images in c#. Most guides offer some lengthy code to scale the image using the Graphics object. While this allow us to set the qualities of the scaling, it has a lot of code (well.. for a lazy guy like me... 50 lines of code with long method names is very hard to read). Moreover, I really don't need the scaled-down image to be of good quality. I just want the process fast, and the result small. So I came up with this:

First you need to reference System.Drawing.dll if it's not reference by default. Then put these in the referencing section:

using System.Drawing;
using System.Drawing.Imaging;

In my test program I did this:

Image img = Image.Fromfile("... source file address");
Size newSize = Size( img.Width/2, img.Height/2);
Image newImg = new Bitmap( img, newSize);
newImg.Save("... new file address", ImageFormat.Jpeg);
img.Dispose();
newImg.Dispose();

And as simple as that, would read in the source image file of any format, and save to the new file address in jpeg format and half the original size. Simple enough!!

Of course, if image quality is a concern, using the Graphics object should yield better results. 

沒有留言:

張貼留言