有时,缩小位图会生成更大的文件.为什么?

Mat*_*ías 5 .net c# bitmap resize-image

我正在尝试编写一种方法来减少每次调用50%的图像的大小,但我发现了一个问题.有时,我最终会得到一个更大的文件大小,而图像实际上只是它的一半.我正在处理DPI和PixelFormat.我还缺少什么?

感谢您的时间.

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;
}
Run Code Online (Sandbox Code Playgroud)

http://imgur.com/lY9BN.png

http://imgur.com/KSka0.png

编辑: 这是缺少的代码:

int width = (int)(bitmap.Width * 0.5f);
int height = (int)(bitmap.Height * 0.5f);
Bitmap resizedBitmap = ResizeBitmap(bitmap, width, height);
resizedBitmap.Save(newFilename);
Run Code Online (Sandbox Code Playgroud)

编辑2: 根据您的评论,这是我找到的解决方案:

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;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*rek 6

您最有可能以低压缩比(高质量)保存jpeg图像.

  • @Matías - 据我所知,压缩率没有存储在标题中,因此一旦保存文件就会丢失信息. (2认同)