Answered by:
Image Resizing using c#

Question
-
Dear all,
Currently I am working on a project which is completely about images.
User may upload high quality pictures of any size....for example 20MB or 100 MB or 150 MB.....
Now my requirement is to store all of those images into database and I have to show in website with different sizes like....thumbnail with 50*50px or 1024*768 like that......Database is going to store Original Image and when for user viewing i have to show same image which fits to the user screen and image size not more than 100kb or 200kb...
While user downloading the image ..... different options to download images like....1446*1024 px or 2564*1446 or 4666*2012
and also how to upload multiple images like in gmail file uploading....
Thanks in advance...
Wednesday, April 13, 2011 12:08 PM
Answers
-
Hi
You'll be interested in the ResizeImage function that takes a System.Drawing.Image, the width and the height as the arguments
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
namespace DoctaJonez.Drawing.Imaging
{
/// <summary>
/// Provides various image untilities, such as high quality resizing and the ability to save a JPEG.
/// </summary>
public static class ImageUtilities
{
/// <summary>
/// A quick lookup for getting image encoders
/// </summary>
private static Dictionary<string, ImageCodecInfo> encoders = null;
/// <summary>
/// A quick lookup for getting image encoders
/// </summary>
public static Dictionary<string, ImageCodecInfo> Encoders
{
//get accessor that creates the dictionary on demand
get
{
//if the quick lookup isn't initialised, initialise it
if (encoders == null)
{
encoders = new Dictionary<string, ImageCodecInfo>();
}
//if there are no codecs, try loading them
if (encoders.Count == 0)
{
//get all the codecs
foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders())
{
//add each codec to the quick lookup
encoders.Add(codec.MimeType.ToLower(), codec);
}
}
//return the lookup
return encoders;
}
}
/// <summary>
/// Resize the image to the specified width and height.
/// </summary>
/// <param name="image">The image to resize.</param>
/// <param name="width">The width to resize to.</param>
/// <param name="height">The height to resize to.</param>
/// <returns>The resized image.</returns>
public static System.Drawing.Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
{
//a holder for the result
Bitmap result = new Bitmap(width, height);
//use a graphics object to draw the resized image into the bitmap
using (Graphics graphics = Graphics.FromImage(result))
{
//set the resize quality modes to high quality
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//draw the image into the target bitmap
graphics.DrawImage(image, 0, 0, result.Width, result.Height);
}
//return the resulting bitmap
return result;
}
/// <summary>
/// Saves an image as a jpeg image, with the given quality
/// </summary>
/// <param name="path">Path to which the image would be saved.</param>
/// <param name="quality">An integer from 0 to 100, with 100 being the
/// highest quality</param>
/// <exception cref="ArgumentOutOfRangeException">
/// An invalid value was entered for image quality.
/// </exception>
public static void SaveJpeg(string path, Image image, int quality)
{
//ensure the quality is within the correct range
if ((quality < 0) || (quality > 100))
{
//create the error message
string error = string.Format("Jpeg image quality must be between 0 and 100, with 100 being the highest quality. A value of {0} was specified.", quality);
//throw a helpful exception
throw new ArgumentOutOfRangeException(error);
}
//create an encoder parameter for the image quality
EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
//get the jpeg codec
ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
//create a collection of all parameters that we will pass to the encoder
EncoderParameters encoderParams = new EncoderParameters(1);
//set the quality parameter for the codec
encoderParams.Param[0] = qualityParam;
//save the image using the codec and the parameters
image.Save(path, jpegCodec, encoderParams);
}
/// <summary>
/// Returns the image codec with the given mime type
/// </summary>
public static ImageCodecInfo GetEncoderInfo(string mimeType)
{
//do a case insensitive search for the mime type
string lookupKey = mimeType.ToLower();
//the codec to return, default to null
ImageCodecInfo foundCodec = null;
//if we have the encoder, get it to return
if (Encoders.ContainsKey(lookupKey))
{
//pull the codec from the lookup
foundCodec = Encoders[lookupKey];
}
return foundCodec;
}
}
}CodeProject articles discussing and sharing source code for scaling images:
- Two Pass Scaling using Filters
- Matrix Transformation of Images in C#, using .NET GDI+
- Resizing a Photographic image with GDI+ for .NET
- Fast Dyadic Image Scaling with Haar Transform
I hope it is helpful.
Cookie Luo[MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
“This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control these sites and has not tested any software or information found on these sites; therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.”
- Proposed as answer by Cor Ligthert Friday, April 15, 2011 6:58 AM
- Marked as answer by Cookie Luo Thursday, April 21, 2011 6:27 AM
Friday, April 15, 2011 6:32 AM
All replies
-
Dear all,
Currently I am working on a project which is completely about images.
User may upload high quality pictures of any size....for example 20MB or 100 MB or 150 MB.....
Now my requirement is to store all of those images into database and I have to show in website with different sizes like....thumbnail with 50*50px or 1024*768 like that......Database is going to store Original Image and when for user viewing i have to show same image which fits to the user screen and image size not more than 100kb or 200kb...
While user downloading the image ..... different options to download images like....1446*1024 px or 2564*1446 or 4666*2012
and also how to upload multiple images like in gmail file uploading....
Thanks in advance...
- Merged by Cookie Luo Friday, April 15, 2011 6:42 AM duplicate
Wednesday, April 13, 2011 12:08 PM -
Hi,
yes, interresting, but I do not see the question here.
Resampling the Images to the desired *spatial-sizes* should not be a problem, whereas resize to filesizes must be calculated in a way which might depend on compression rates and so on. So if you want to save them uncompressed you *can* quite easiliy calculate the resulting size, but if it is a format like jpg you'll have to examine each image deeply in combination with the [complete understanding of the] encoding-proceedure to calculate reliable presumed filesizes or do that on experience-values...
Regards,
Thorsten
Wednesday, April 13, 2011 12:40 PM -
The Bitmap class has a function getThumbnailImage of desired pixel dimensions. But the size constraint is little complex than you just don't worry about the size. As the pixel dimensions are same and the entropy more are less same then size won't vary too much.
Wednesday, April 13, 2011 1:13 PM -
Hi
You'll be interested in the ResizeImage function that takes a System.Drawing.Image, the width and the height as the arguments
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
namespace DoctaJonez.Drawing.Imaging
{
/// <summary>
/// Provides various image untilities, such as high quality resizing and the ability to save a JPEG.
/// </summary>
public static class ImageUtilities
{
/// <summary>
/// A quick lookup for getting image encoders
/// </summary>
private static Dictionary<string, ImageCodecInfo> encoders = null;
/// <summary>
/// A quick lookup for getting image encoders
/// </summary>
public static Dictionary<string, ImageCodecInfo> Encoders
{
//get accessor that creates the dictionary on demand
get
{
//if the quick lookup isn't initialised, initialise it
if (encoders == null)
{
encoders = new Dictionary<string, ImageCodecInfo>();
}
//if there are no codecs, try loading them
if (encoders.Count == 0)
{
//get all the codecs
foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders())
{
//add each codec to the quick lookup
encoders.Add(codec.MimeType.ToLower(), codec);
}
}
//return the lookup
return encoders;
}
}
/// <summary>
/// Resize the image to the specified width and height.
/// </summary>
/// <param name="image">The image to resize.</param>
/// <param name="width">The width to resize to.</param>
/// <param name="height">The height to resize to.</param>
/// <returns>The resized image.</returns>
public static System.Drawing.Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
{
//a holder for the result
Bitmap result = new Bitmap(width, height);
//use a graphics object to draw the resized image into the bitmap
using (Graphics graphics = Graphics.FromImage(result))
{
//set the resize quality modes to high quality
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//draw the image into the target bitmap
graphics.DrawImage(image, 0, 0, result.Width, result.Height);
}
//return the resulting bitmap
return result;
}
/// <summary>
/// Saves an image as a jpeg image, with the given quality
/// </summary>
/// <param name="path">Path to which the image would be saved.</param>
/// <param name="quality">An integer from 0 to 100, with 100 being the
/// highest quality</param>
/// <exception cref="ArgumentOutOfRangeException">
/// An invalid value was entered for image quality.
/// </exception>
public static void SaveJpeg(string path, Image image, int quality)
{
//ensure the quality is within the correct range
if ((quality < 0) || (quality > 100))
{
//create the error message
string error = string.Format("Jpeg image quality must be between 0 and 100, with 100 being the highest quality. A value of {0} was specified.", quality);
//throw a helpful exception
throw new ArgumentOutOfRangeException(error);
}
//create an encoder parameter for the image quality
EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
//get the jpeg codec
ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
//create a collection of all parameters that we will pass to the encoder
EncoderParameters encoderParams = new EncoderParameters(1);
//set the quality parameter for the codec
encoderParams.Param[0] = qualityParam;
//save the image using the codec and the parameters
image.Save(path, jpegCodec, encoderParams);
}
/// <summary>
/// Returns the image codec with the given mime type
/// </summary>
public static ImageCodecInfo GetEncoderInfo(string mimeType)
{
//do a case insensitive search for the mime type
string lookupKey = mimeType.ToLower();
//the codec to return, default to null
ImageCodecInfo foundCodec = null;
//if we have the encoder, get it to return
if (Encoders.ContainsKey(lookupKey))
{
//pull the codec from the lookup
foundCodec = Encoders[lookupKey];
}
return foundCodec;
}
}
}CodeProject articles discussing and sharing source code for scaling images:
- Two Pass Scaling using Filters
- Matrix Transformation of Images in C#, using .NET GDI+
- Resizing a Photographic image with GDI+ for .NET
- Fast Dyadic Image Scaling with Haar Transform
I hope it is helpful.
Cookie Luo[MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
“This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control these sites and has not tested any software or information found on these sites; therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.”
- Proposed as answer by Cor Ligthert Friday, April 15, 2011 6:58 AM
- Marked as answer by Cookie Luo Thursday, April 21, 2011 6:27 AM
Friday, April 15, 2011 6:32 AM -
Albin,
I would use the GetThumbail for quick viewing and put that in the database as an image in a database is extremely slow to handle.
However, I think the OP is in this case better of for a method like Cookie shows (I hope you don't mind that I did not check that one on mistakes)
:-)
More for the OP than for you of course.
Success
CorFriday, April 15, 2011 6:58 AM -
Hi Cor Ligthert,
Interesting to know. Well, but I think OP not going to store the thumbnails back to database.Cookie shown a great effort. I will surely try.
Thanks
Friday, April 15, 2011 9:32 AM