问题
I've been using this method to resize uploaded .JPG
images to a max width, but it's resulting in images being larger in kb than the source. What am I doing wrong? Is there something else I need to do when saving the new image?
I've tried all sorts of combinations of PixelFormat
, e.g. PixelFormat.Format16bppRgb555
E.g: source image is a .JPG
1900w, trying to resize to 1200w...
- Source file is 563KB,
- resized file is 926KB or larger, even 1.9MB
public static void ResizeToMaxWidth(string fileName, int maxWidth)
{
Image image = Image.FromFile(fileName);
if (image.Width > maxWidth)
{
double ratio = ((double)image.Width / (double)image.Height);
int newHeight = (int)Math.Round(Double.Parse((maxWidth / ratio).ToString()));
Bitmap resizedImage = new Bitmap(maxWidth, newHeight);
Graphics graphics = Graphics.FromImage(resizedImage);
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High
Rectangle rectDestination = new Rectangle(0, 0, maxWidth, newHeight);
graphics.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
graphics.Dispose();
image.Dispose();
resizedImage.Save(fileName);
resizedImage.Dispose();
}
image.Dispose();
}
回答1:
You need to specify that you want to save it as the jpeg format:
resizedImage.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
Otherwise it will default to saving as BMP / PNG (I can't remember which).
来源:https://stackoverflow.com/questions/43017831/image-resize-results-in-massively-larger-file-size-than-original-c-sharp