1

I am trying to watermark a jpg image with another jpg image. It's working fine if I store the resulting image as a new image. Is it possible to just update the original image file with the watermark image? I don't need to store it as a different file.

Here is my code:

//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();
hakre
  • 193,403
  • 52
  • 435
  • 836

2 Answers2

3

Image.FromFile retains a lock on the original file. Rather than create the image directly from the file, try opening the file from a FileStream and creating the image from that stream. This way you can control when the file's lock is released.

try this:

public static Image CreateImage(string filePath)
{
    using(var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        return Image.FromStream(fs);
}

A bit more info. MSDN mentions that Image.FromFile will retain the lock until the image is disposed. http://msdn.microsoft.com/en-us/library/stf701f5.aspx

I just realized that the FromStream method suggests that the stream remain open. If you still have problems, try reading the bytes into a memorystream. In this example, the memorystream isn't disposed. It would be a good idea to dispose of the stream when you've adapted this to your code. :)

public static Image CreateImage(string filePath)
{
        var bytes = File.ReadAllBytes(filePath);
        var ms = new MemoryStream(bytes);
        return Image.FromStream(ms);
}
Nick VanderPyle
  • 2,939
  • 3
  • 26
  • 33
1

It is probably because Image.FromFile method is locking the file.
See this answer for a method on how to load the file without locking it: https://stackoverflow.com/a/3389126/214222

Community
  • 1
  • 1
Jens Granlund
  • 4,950
  • 1
  • 31
  • 31