c# - 在 C# 中为 jpg 文件加水印

标签 c# watermark

我正在尝试用另一个 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/

相关文章:

ruby-on-rails - 载波水印图像

c# - Moq VerifySet(Action) 替换过时的表达式编译错误

c# - 在可变长度字符串的末尾添加固定数量的空格

C# - 读取和预览字体

c# - 在编译时生成一个 Guid

C#:保存 JPEG 时水印图像质量差

c# - 使用 OpenXml 在现有的 word 文档中动态地向表中添加行

c++ - 如何将水印或 png 或位图添加到 CTreeCtrl 的背景中?

PHP:将透明 PNG 添加到具有不透明度的 JPEG

wpf - 如何将水印文本添加到 wpf 中的文本框?