public void MinimizeImageSize(string sourcePath, string outputPath, int maxWidth, int maxHeight, long quality)
{
using (Image sourceImage = Image.FromFile(sourcePath))
{
int width = sourceImage.Width;
int height = sourceImage.Height;
// Scale the image to fit within the specified maximum dimensions
if (width > maxWidth || height > maxHeight)
{
if ((double)width / maxWidth > (double)height / maxHeight)
{
height = (int)(height * ((double)maxWidth / width));
width = maxWidth;
}
else
{
width = (int)(width * ((double)maxHeight / height));
height = maxHeight;
}
}
// Create a new bitmap with the scaled dimensions
using (Bitmap outputBitmap = new Bitmap(width, height))
{
using (Graphics graphics = Graphics.FromImage(outputBitmap))
{
// Set the image quality and compression settings
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, quality);
// Draw the scaled image onto the new bitmap
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.DrawImage(sourceImage, new Rectangle(0, 0, width, height));
// Save the new image to the specified output path
outputBitmap.Save(outputPath, GetEncoderInfo("image/jpeg"), encoderParams);
}
}
}
}
private ImageCodecInfo GetEncoderInfo(string mimeType)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec
Aucun commentaire:
Enregistrer un commentaire