Hello,
I'm trying to write a method to reduce the size of any image 50% each time is called but I've found a problem. Sometimes, I end up with a bigger filesize while the image is really just half of what it was. I'm taking care of DPI and PixelFormat. What else am I missing?
Thank you for your time.
public Bitmap ResizeBitmap(Bitmap origBitmap, int nWidth, int nHeight)
{
Bitmap newBitmap = new Bitmap(nWidth, nHeight, origBitmap.PixelFormat);
newBitmap.SetResolution(
origBitmap.HorizontalResolution,
origBitmap.VerticalResolution);
using (Graphics g = Graphics.FromImage((Image)newBitmap))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(origBitmap, 0, 0, nWidth, nHeight);
}
return newBitmap;
}
Edit: Here's the missing code:
int width = (int)(bitmap.Width * 0.5f);
int height = (int)(bitmap.Height * 0.5f);
Bitmap resizedBitmap = ResizeBitmap(bitmap, width, height);
resizedBitmap.Save(newFilename);
Edit 2: Based on your comments, this is the solution I've found:
private void saveAsJPEG(string savingPath, Bitmap bitmap, long quality)
{
EncoderParameter parameter = new EncoderParameter(Encoder.Compression, quality);
ImageCodecInfo encoder = getEncoder(ImageFormat.Jpeg);
if (encoder != null)
{
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = parameter;
bitmap.Save(savingPath, encoder, encoderParams);
}
}
private ImageCodecInfo getEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
if (codec.FormatID == format.Guid)
return codec;
return null;
}