SO中的问题,例如this one或this one已经讨论了这个异常的很多原因,但是没有一个可以帮助我找出我的问题,而且我仍然无法弄清楚为什么会发生这种情况。
我在尝试保存时遇到此错误(代码如下)。我得到的最奇怪的事情是 - 这个错误是随机图像发生的(现在我们说“随机”,因为我还不知道确切的问题)。仅对于数千张中的特定图像,我遇到了这个问题。
这是尝试时一张成功的图片和一张失败的图片。
<强>1。 2009-05-23_00.51.39.jpg
图片尺寸:768x1024
大小:87KB
位深度:24
颜色表示:sRGB
<强>2。 2009-05-23_00.52.50.jpg
图片尺寸:768x1024
大小:335KB
位深度:24
颜色表示:sRGB
对于图像 #1,该过程进展顺利,没有错误。然而,对于图像#2,我不断收到此错误。如您所见,图像几乎相同。两者都是 .jpg,尺寸相同,并且大多数属性都相同。
方法如下。
public static Stream GetImageBytes(Stream fileStream, int maxWidth, int maxHeight, bool showCopyRight, string link, int fillColor = 0xFFFFFF)
{
var img = Image.FromStream(fileStream);
if (maxHeight != 0 && img.Height > maxHeight)
ResizeByHeight(ref img, maxHeight, fillColor.ToString("X6"));
if (maxWidth != 0 && img.Width > maxWidth)
ResizeByWidth(ref img, maxWidth, fillColor.ToString("X6"));
if (showCopyRight)
img = ApplyWatermark(ref img, "watermark.png", link);
var ms = new MemoryStream();
//problem is here
img.Save(ms, ImageFormat.Jpeg);
img.Dispose();
return ms;
}
评论后编辑。
好的,这是水印方法
private static Bitmap ApplyWatermark(ref Image img, string watermarkPathPng, string link) {
const int x = 0;
var y = img.Height - 20;
string watermarkText;
if (img.Width <= 220) {
watermarkText = "shorter copy";
} else {
if (img.Width < 500)
watermarkText = "longer copy";
else
watermarkText = "full copy " + link;
}
var bp = new Bitmap(img);
img.Dispose();
using (var gr = Graphics.FromImage(bp)) {
var watermark = Image.FromFile(watermarkPathPng);
gr.DrawImage(watermark, x, y, watermark.Width, watermark.Height);
watermark.Dispose();
gr.DrawString(watermarkText, new Font(new FontFamily("Batang"), 13, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.Black, 5, y + 5);
}
return bp;
}
我在这个方法中使用Bitmap
的原因是我之前遇到过索引像素问题并且解决了这个问题。
最佳答案
尝试复制图像,而不是直接在您加载的图像上进行操作。通常,gdi 错误是由于您试图更改您认为自己“拥有”的内容,而加载程序认为它拥有它。
由于它只发生在某些图像上,请检查三种处理方法中的逻辑 - 也许只有当您需要进行垂直调整大小时才会发生故障,在这种情况下查找该方法中的错误。我们的可能是图像必须通过您的多种方法进行处理。
您返回 img 并在 ApplyWatermark() 中通过引用传递它也很可疑。在这里检查你的逻辑。
关于c# - 对于随机图像,GDI+ 中发生一般错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21504195/