我正在开展一个项目,我必须使用fabric.js从前端绘制文字。我有代码发送json用于绘制字符串,即canvas.tojson()
。
在服务器端,我在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 :(得分: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 :(得分: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);