问题描述
我正在使用以下代码来压缩图像,这做得很好,但是我想使用压缩后的图像而不保存它。因此,现在我必须保存图像,然后再次读取它,这很慢。
I am using the following code to compress an image and it does a nice job but I want to use the compressed image not save it. So right now I have to save the image then read it in again which is slow. Is there a way of compressing it with out saving it.
private void compress(System.Drawing.Image img, long quality, ImageCodecInfo codec)
{
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
img.Save("check1.jpg", codec, parameters);
}
private static ImageCodecInfo GetCodecInfo(string mimeType)
{
foreach (ImageCodecInfo encoder in ImageCodecInfo.GetImageEncoders())
if (encoder.MimeType == mimeType)
return encoder;
throw new ArgumentOutOfRangeException(
string.Format("'{0}' not supported", mimeType));
}
推荐答案
有一个,因此您可以将其直接保存到 MemoryStream
,而无需保存到磁盘/重新加载。
There is an overload that takes a Stream
so you can save it straight to a MemoryStream
and won't need to save to disk/reload.
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
var ms = new MemoryStream();
img.Save(ms, codec, parameters);
//Do whatever you need to do with the image
//e.g.
img = Image.FromStream(ms);
在注释中提到参数无效异常的原因是因为在尝试调用 FromStream
之前不会处理图像,因此您需要对其进行处理。另外,我不知道您如何调用此方法,但您可能应该对其进行更新以返回 MemoryStream
。
The reason you're getting the "Parameter not valid" exception you mention in the comments is because the image isn't being disposed of before you try to call FromStream
, so you'll need to dispose it. Also, I don't know how you're calling this method, but you should probably update it to return the MemoryStream
.
private void compress(System.Drawing.Image img, long quality, ImageCodecInfo codec)
{
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
var ms = new MemoryStream();
img.Save(ms, codec, parameters);
return ms;
}
public void MyMethod()
{
MemoryStream ms;
using(var img = Image.FromFile("myfilepath.img"))
{
ms = compress(img, /*quality*/, /*codec*/);
}
using(var compressedImage = Image.FromStream(ms))
{
//Use compressedImage
}
}
注意我如何从压缩返回 ms
。另外,更重要的是,我们如何将初始 img
包裹在 using
语句中,这将正确处理文件句柄,以及之后被处理掉后,创建第二个 compressedImage
,它也在中使用
,因此它将完成操作后, 也将得到适当处理。
Notice how I return ms
from compress and capture it. Also, more importantly, how we wrap the initial img
in a using
statement which will dispose the file handle correctly, and after that gets disposed create the second compressedImage
which is also in a using
so it will also get disposed of properly when you're done.
这篇关于压缩图像而不保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!