我正在尝试用另一个 jpg 图像为 jpg 图像加水印。如果我将生成的图像存储为新图像,它工作正常。是否可以只用水印图像更新原始图像文件?我不需要将它存储为不同的文件。
这是我的代码:
//watermark image
Bitmap sizedImg = (Bitmap)System.Drawing.Image.FromFile(@"C:\report branding.jpg");
//original file
System.Drawing.Bitmap template=(System.Drawing.Bitmap)System.Drawing.Image.FromFile(@"C:\CentralUtahCombined1.jpg");
Graphics g = Graphics.FromImage(template);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.DrawImage(sizedImg, new Point(template.Width - sizedImg.Width,
template.Height - sizedImg.Height));
//watermarking the image but saving it as a different image file - here if I //provide the name as the original file name, it throws an error
string myFilename = @"C:\CentralUtah.jpg";
template.Save(myFilename);
template.Dispose();
sizedImg.Dispose();
g.Flush();
最佳答案
Image.FromFile 保留对原始文件的锁定。不要直接从文件创建图像,而是尝试从 FileStream 打开文件并从该流创建图像。这样您就可以控制何时释放文件的锁定。
试试这个:
public static Image CreateImage(string filePath)
{
using(var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
return Image.FromStream(fs);
}
更多信息。 MSDN 提到 Image.FromFile 将保留锁,直到图像被处理。 http://msdn.microsoft.com/en-us/library/stf701f5.aspx
我刚刚意识到 FromStream 方法建议流保持打开状态。如果仍有问题,请尝试将字节读入内存流。在此示例中,未释放内存流。当您将流调整为您的代码时,处理流是个好主意。 :)
public static Image CreateImage(string filePath)
{
var bytes = File.ReadAllBytes(filePath);
var ms = new MemoryStream(bytes);
return Image.FromStream(ms);
}
关于c# - 在 C# 中为 jpg 文件加水印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15512364/