奇怪的 GDI+行为
我制定了一种根据图像质量压缩ImageSize的方法。它的代码是
public static Image CompressImage(string imagePath, long quality)
{
Image srcImg = LoadImage(imagePath);
//Image srcImg = Image.FromFile(imagePath);
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
ImageCodecInfo encoder = GetCodecInfo("image/jpeg");
srcImg.Save("d:\\creatives\\abcd123.jpg", encoder, parameters);
}
public static Image LoadImage(string filename)
{
using (FileStream fs = new FileStream(filename, FileMode.Open))
{
return(Image.FromStream(fs));
}
}
现在,当我按原样运行此代码时,它在保存 srcImg(func #1 中的最后一行)时给出了“通用 GDI+ 异常”,但是当我取消注释第二行并使用 Image. FromFile 一切正常。
为什么 ??
I have made a method to CompressImageSize according to Image quality. The code for it is
public static Image CompressImage(string imagePath, long quality)
{
Image srcImg = LoadImage(imagePath);
//Image srcImg = Image.FromFile(imagePath);
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
ImageCodecInfo encoder = GetCodecInfo("image/jpeg");
srcImg.Save("d:\\creatives\\abcd123.jpg", encoder, parameters);
}
public static Image LoadImage(string filename)
{
using (FileStream fs = new FileStream(filename, FileMode.Open))
{
return(Image.FromStream(fs));
}
}
Now, when i run this code as is it gives me a 'Generic GDI+ exception' while saving the srcImg(last line in func #1), BUT when i uncomment the 2nd line and load the image using Image.FromFile everything works fine.
Why ??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
根据 MSDN:
这里,您的流位于 using 块中,因此在图像的生命周期结束之前关闭。
According to MSDN:
Here your stream is in a using block and thus closed before the end of the lifetime of the image.
您应该重写您的代码:
在这种情况下,
using
的构造是错误的,因为FileStream
需要处于活动状态才能使用您的图像。You should rewrite your code:
Construction
using
is wrong in this case becauseFileStream
needs to be alive for using your Image.一个疯狂的猜测...图像是 IDisposable。你是在循环中调用这个还是什么?尝试将图像本身放入 using() 块中?
A wild guess... Image is IDisposable. Are you calling this in a loop or something? Try putting your Image itself in a using() block?
在
LoadImage
的最后,包含Image的FileStream被释放。这还为时过早;文件流需要处于活动状态才能供调用LoadImage
的方法使用。请参阅 MSDN 上的使用。
In the end of
LoadImage
, the FileStream containing the Image is disposed. This is too soon; the file stream needs to be alive for use by the method callingLoadImage
.See using on MSDN.
Image.FromFile() 存在各种问题...
上述语句不会关闭文件流,如果您想再次访问文件或删除它,则会产生问题。我会这样写你的函数。
这将保证我的文件将在使用范围结束时关闭。
There are various issues with Image.FromFile()...
The above statement will not close the file stream and that will create problems if you want to access file again or delete it. I would write your function this way.
This will guarentee that my file will be closed at the end of using scope.
修复,但对我来说 Dispose 调用是 .net 框架中的一个错误...
Fix , but for me the Dispose call is a bug in .net framework...