In my project, I need to resize the image (e.g.1080 to 720), reduce the file size (may be resolution, 0-100) which is uploaded by client, so that they can then download it.
I can reduce the file size (by resolution) in C#, but not scale and resize. Can anyone tell me how to do that, even using APIs or frameworks.
My reduce resolution code in C#: (from this post)
public static void Saveimage(string path, Image img, int quality)
{
if (quality < 0 || quality > 100)
throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");
// Encoder parameter for image quality
EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality);
string imageType = GetImageFormat(img);
ImageCodecInfo imageCodec = GetEncoderInfo(imageType);
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
img.Save(path, imageCodec, encoderParams);
}
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
// Get image codecs for all image formats
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
// Find the correct image codec
for (int i = 0; i < codecs.Length; i++)
if (codecs[i].MimeType == mimeType)
return codecs[i];
return null;
}
public static string GetImageFormat(Image img)
{
if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
return "image/jpeg";
if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))
return "image/png";
if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Tiff))
return "image/tiff";
else
return "image/jpeg";
}
Call:
Saveimage(@"C:\mypath", myImage, 1);