2013-03-19 26 views
1

我想用另一個jpg圖像水印一個jpg圖像。如果將結果圖像存儲爲新圖像,它工作正常。是否可以用水印圖像更新原始圖像文件?我不需要將它作爲一個不同的文件存儲。C#中的水印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(); 
+0

什麼是拋出的異常? – 2013-03-19 23:29:33

回答

3

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); 
} 
+0

這不起作用,因爲'Image.FromStream'需要流不被處置。 – 2013-03-19 23:38:35

+0

克隆內存中的圖像或創建並將其寫入新的圖像。然後,您可以處理原件並保存在原件上。 – 2013-03-19 23:43:46

+0

@JensGranlund你發現我的錯誤。 :)我剛剛注意到,在你評論的msdn中。 – 2013-03-19 23:50:22