降低质量后,从功能返回位图图像

时间:2015-02-09 06:22:07

标签: c# bitmapimage

我从互联网这个功能。这将图像的大小减小到50%。 现在我无法返回下面的位图图像格式函数。

我无法找到当前位图图像达到50%的任何方法并将其返回。

我是否需要创建内存流然后将其保存在那里?

//reduce Image size
public void ReduceImageSize(Bitmap bmp1)
{
    var jgpEncoder = GetEncoder(ImageFormat.Jpeg);
    // Create an Encoder object based on the GUID 
    // for the Quality parameter category.
    var myEncoder = Encoder.Quality;
    // Create an EncoderParameters object. 
    // An EncoderParameters object has an array of EncoderParameter 
    // objects. In this case, there is only one 
    // EncoderParameter object in the array.
    var myEncoderParameters = new EncoderParameters(1);

    var myEncoderParameter = new EncoderParameter(myEncoder, 50L);
    myEncoderParameters.Param[0] = myEncoderParameter;
    //rather than saving it should set to the current bitmap image.
    //bmp1.Save(@"c:\TestPhoto\TestPhotoQualityFifty.jpg", jgpEncoder, myEncoderParameters);


}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
    var codecs = ImageCodecInfo.GetImageDecoders();
    foreach (var codec in codecs)
    {
        if (codec.FormatID == format.Guid)
        {
            return codec;
        }
    }
    return null;
}
}

1 个答案:

答案 0 :(得分:2)

您应该只将文件保存到内存中,然后从该内存构建一个新图像:

using(var ram = new MemoryStream())
{
    bmp1.Save(ram, jgpEncoder, myEncoderParameters);
    ram.Seek(0, SeekOrigin.Begin); // reset stream to start so it can be read again
    return new Bitmap(ram);
}