2016-11-25 33 views
-1

嗨我工作的項目,我必須從前端繪製文本使用fabric.js我有代碼發送json的繪製字符串即canvas.tojson() 在服務器端我有一個問題在C#中。我必須用相同的文件名保存圖像。如果我嘗試saveing之前刪除原始文件,它說文件已經被其他程序使用,如果我overrite它沒有這樣做,要麼我怎麼能保存具有相同名稱的文件圖像繪製在圖像上繪製字符串並保存爲相同的名稱c#

這裏後,我的代碼

string file = "D:\\Folder\\file.jpg"; 
      Bitmap bitMapImage = new Bitmap(file); 
      Graphics graphicImage = Graphics.FromImage(bitMapImage); 
      graphicImage.SmoothingMode = SmoothingMode.AntiAlias; 
      graphicImage.DrawString("That's my boy!",new Font("Arial", 12, FontStyle.Bold),SystemBrushes.WindowText, new Point(100, 250)); 
      graphicImage.DrawArc(new Pen(Color.Red, 3), 90, 235, 150, 50, 0, 360); 

      System.IO.File.Delete(file); 

      bitMapImage.Save(file, ImageFormat.Jpeg); 
+0

另請參見此處(http://stackoverflow.com/questions/37736815/overwrite-image-picturebox-in-c-sharp/37741101?s=2|0.0000#37741101) – TaW

回答

2

只是克隆原來的位圖和丟棄原,使其釋放文件...

Bitmap cloneImage = null; 
using (Bitmap bitMapImage = new Bitmap(file)) 
{ 
    cloneImage = new Bitmap(bitMapImage); 
} 


using (cloneImage) 
{ 
    Graphics graphicImage = Graphics.FromImage(cloneImage); 
    graphicImage.SmoothingMode = SmoothingMode.AntiAlias; 
    graphicImage.DrawString("That's my boy!", new Font("Arial", 12, FontStyle.Bold), SystemBrushes.WindowText, new Point(100, 250)); 
    graphicImage.DrawArc(new Pen(Color.Red, 3), 90, 235, 150, 50, 0, 360); 

    System.IO.File.Delete(file); 

    cloneImage.Save(file, ImageFormat.Jpeg); 
} 
1

在參考this answer,你可以從一個文件流得到的位圖和更改之前其丟棄圖片:

 Bitmap bitMapImage; 
     using (var fs = new System.IO.FileStream(file, System.IO.FileMode.Open)) 
     { 
      bitMapImage = new Bitmap(fs); 
     } 

     Graphics graphicImage = Graphics.FromImage(bitMapImage); 
     graphicImage.SmoothingMode = SmoothingMode.AntiAlias; 
     graphicImage.DrawString("That's my boy!",new Font("Arial", 12, FontStyle.Bold),SystemBrushes.WindowText, new Point(100, 250)); 
     graphicImage.DrawArc(new Pen(Color.Red, 3), 90, 235, 150, 50, 0, 360);   

     bitMapImage.Save(file, ImageFormat.Jpeg); 
相關問題