Sometimes, we need to compress the image files while maintaining the image quality. This can be achieved by the following C# implementation.
Usage: zoomImage(path, zoom).Save(destImagePath);
private Image zoomImage(string fileName, float zoom = 0.25f) // set quality to 1-100, eg 50
{
Image img = Image.FromFile(fileName);
Image zoomedImage = new Bitmap(Image.FromFile(fileName), Convert.ToInt32(img.Width * zoom), Convert.ToInt32(img.Height * zoom));
int quality = 100;
var myImageCodecInfo = ImageCodecInfo.GetImageEncoders().Where(encoder => encoder.MimeType == "image/jpeg").FirstOrDefault();
var myEncoderParameters = new EncoderParameters(1);
myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
var stream = new MemoryStream();
zoomedImage.Save(stream, myImageCodecInfo, myEncoderParameters);
var newImage = Image.FromStream(stream);
var g = Graphics.FromImage(newImage);
g.InterpolationMode = InterpolationMode.Default;
g.DrawImage(newImage, new Rectangle(Point.Empty, newImage.Size), 0, 0,
newImage.Width, newImage.Height, GraphicsUnit.Pixel, new ImageAttributes());
return newImage;
}
No comments:
Post a Comment