In this blog post I will explain in short how to load and re size an image in C# and save the resulting image in a file.
Actually the process is very easy. Lets break it in chunks
Loading image from a file
.NET has multiple ways to load an image.
1) From a file
2) From a Stream object
3) From a GDI Bitmap object
For this post we will only load image from a File.Loading image from file is straight forward. It requires calling static method FromFile of Image class , passing the file path as a parameter. Here is how
Re-sizing image
As we now have Image instance we have to re size it. For re-sizing we will use one overload of Bitmap class constructor which takes Image instance and new width and height for scaling. So here is the one liner to do this job
Saving the resulting image
We have a Bitmap containing scaled version of our original image.Now we will save it to a file. Saving a Bitmap/Image in file is very simple.
So simple! . Lets just put our code together for easy use.
Now we can load,re-size and save scaled image using one line of code
ImageHelper.ResizeAndSave("C:\\random-stuff-mine.jpg","C:\\random-stuff-mine2.jpg",100,100);
Actually the process is very easy. Lets break it in chunks
Loading image from a file
.NET has multiple ways to load an image.
1) From a file
2) From a Stream object
3) From a GDI Bitmap object
For this post we will only load image from a File.Loading image from file is straight forward. It requires calling static method FromFile of Image class , passing the file path as a parameter. Here is how
Image myImage=Image.FromFile(sourcePath);
Re-sizing image
As we now have Image instance we have to re size it. For re-sizing we will use one overload of Bitmap class constructor which takes Image instance and new width and height for scaling. So here is the one liner to do this job
Bitmap bmp=new Bitmap(myImage,newWidth,newHeight);
Saving the resulting image
We have a Bitmap containing scaled version of our original image.Now we will save it to a file. Saving a Bitmap/Image in file is very simple.
bmp.Save(destFile);
So simple! . Lets just put our code together for easy use.
public class ImageHelper
{
public static void ResizeAndSave(string sourceFile,string destFile,int newWidth,int newHeight)
{
Image originalImage=Image.FromFile(sourceFile);
Bitmap bmpScaled=new Bitmap(originalImage,newWidth,newHeight);
bmpScaled.Save(destFile);
}
}
Now we can load,re-size and save scaled image using one line of code
ImageHelper.ResizeAndSave("C:\\random-stuff-mine.jpg","C:\\random-stuff-mine2.jpg",100,100);
Comments
Post a Comment
Share your wisdom