顯示具有 C# 標籤的文章。 顯示所有文章
顯示具有 C# 標籤的文章。 顯示所有文章

2012年5月10日 星期四

Re-sizing images for website

With my super short image re-sizing procedure in my last post, I wrote a class the abstract an image file into an object. Within it, is a function to scale the image. Then I ran into a problem:
Say we have a image that's 800 x 600, and I want to resize it to fit a 600 x 200 rectangle. By using my procedures, the code:
new Bitmap(img, new Size( 600, 200));
create a image that's 600x200 from the original image. Well... the problem is that the image scale is off.
If we are indeed resizing pictures to fit a predefined windows size of 800x600, or perhaps 400x300, with my old procedures, the result would have some photos being stretched. Who would want to actually view their photos like that?
So a different method is needed that would check the original picture size against the desired size, and attempt to fit the picture in it without changing the aspect ratio. Which should be rather simple to implement.

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.