Reducing JPEG image quality without saving

2020-07-30 01:28发布

I am trying to programatically reduce the quality of an image in the fastest way possible. Right now, I am able to read image from byte[], then as a MemoryStream read it to Bitmap and via Drawing.Imaging.Encoder.Quality change its quality when saving to desired 20L.

I would like to know if there is a way to do this without saving the whole image. Is there way to just change the bitmap bmp1, or create a new bitmap that would have the image quality reduced?

byte[] imageBytes = convertImageToByteArray(bmpScreenshot);
MemoryStream mem = new MemoryStream(imageBytes);
using (Bitmap bmp1 = (Bitmap)Image.FromStream(mem))
{

     ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
     ImageCodecInfo jgpEncoder = codecs[1];

     System.Drawing.Imaging.Encoder myEncoder =
     System.Drawing.Imaging.Encoder.Quality;

     myEncoderParameter = new EncoderParameter(myEncoder, 20L);
     myEncoderParameters.Param[0] = myEncoderParameter;
     bmp1.Save(@"C:\TestPhotoQuality20L.jpg", jgpEncoder, myEncoderParameters);
}

2条回答
Rolldiameter
2楼-- · 2020-07-30 01:57

David is right you can do like this.

EncoderParameters myEncoderParameters = new EncoderParameters(1);
myEncoderParameters.Param[0] = new EncoderParameter(myEncoder, 20L);
MemoryStream ms = new MemoryStream();
bmp1.Save(ms, format);
Image imgImage = Image.FromStream(ms);
查看更多
来,给爷笑一个
3楼-- · 2020-07-30 02:04

Instead of saving bmp1 to a file. You can save it to another MemoryStream. Then you could load a new bitmap from this MemoryStream.

查看更多
登录 后发表回答