newbie: how to scale image in memory?

D

Dan

A simple console application needs to get a number of image files and resize
them as required by some parameters, either keeping or discarding the
original aspect ratio. I can load an image by creating a new Bitmap object
from an image file name, even if this seems to take a relatively long time
(and, more important, spend a lot of memory) for somewhat large images (is
there a more efficient method?); then I calculate the new desired size;
finally, I should resize it and save to a new file. How can I resize this
loaded Bitmap?

e.g.:
Bitmap bmp = new Bitmap("someimage.jpg");
int newWidth = 100, newHeigth = 150;

now how can I resize bmp to newWidth,newHeigth?

Thanks folks!
 
N

Noah Coad [MVP .NET/C#]

I've written myself a utility to do just what you're trying to do, resize a
picture from the command line. Here is a method from my code that resizes
an image keeping the aspect ratio by supplying a maximum width and height
the new image should fit into.

private Image ConvertImage(Image source, int MaxWidth, int MaxHeight)
{
float MaxRatio = MaxWidth / (float) MaxHeight;
float ImgRatio = source.Width / (float) source.Height;

if (source.Width > MaxWidth)
return new Bitmap(source, new Size(MaxWidth, (int) Math.Round(MaxWidth /
ImgRatio, 0)));

if (source.Height > MaxHeight)
return new Bitmap(source, new Size((int) Math.Round(MaxWidth * ImgRatio,
0), MaxHeight));

return source;
}

By the way, there is a kewl little tool Microsoft created as part of their
PowerToys collection that directly replaced my utilty for what I needed.
You may find it kewl too. It is an image resizer that integrates into
Windows Explorer.
http://www.microsoft.com/windowsxp/pro/downloads/powertoys.asp


-Noah Coad
Microsoft MVP & MCP [.NET/C#]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top