在c#中写入图像上的文本
我有以下问题。 我想在位图图像中制作一些图形,如债券forms
我可以用图像写一个文字
但我会在不同的位置写更多的文字
Bitmap a = new Bitmap(@"path\picture.bmp"); using(Graphics g = Graphics.FromImage(a)) { g.DrawString(....); // requires font, brush etc }
如何编写文本并保存并在保存的图像中写入另一个文本
要绘制多个字符串,请多次调用graphics.DrawString
。 您可以指定绘制字符串的位置。 这个例子我们将绘制两个字符串“Hello”,“Word”(蓝色前面的“Hello”,红色中的“Word”):
string firstText = "Hello"; string secondText = "World"; PointF firstLocation = new PointF(10f, 10f); PointF secondLocation = new PointF(10f, 50f); string imageFilePath = @"path\picture.bmp" Bitmap bitmap = (Bitmap)Image.FromFile(imageFilePath);//load the image file using(Graphics graphics = Graphics.FromImage(bitmap)) { using (Font arialFont = new Font("Arial", 10)) { graphics.DrawString(firstText, arialFont, Brushes.Blue, firstLocation); graphics.DrawString(secondText, arialFont, Brushes.Red, secondLocation); } } bitmap.Save(imageFilePath);//save the image file
编辑: “我添加一个加载并保存代码”。
您可以随时在Image.FromFile
打开位图文件,并使用上面的代码在其上绘制新文本。 然后保存图像文件bitmap.Save
这是一个对Graphics.DrawString
的调用示例,取自此处 :
g.DrawString("My\nText", new Font("Tahoma", 40), Brushes.White, new PointF(0, 0));
它显然依赖于安装了一个名为Tahoma
的字体。
Brushes
类有许多内置画笔。
另请参见Graphics.DrawString
的MSDN页面。
为了保存对同一文件的更改,我不得不将Jalal Said的答案和NSGaga的答案结合起来。 您需要基于旧的Bitmap对象创建一个新的Bitmap对象,处理旧的Bitmap对象,然后使用新对象进行保存:
string firstText = "Hello"; string secondText = "World"; PointF firstLocation = new PointF(10f, 10f); PointF secondLocation = new PointF(10f, 50f); string imageFilePath = @"path\picture.bmp"; Bitmap newBitmap; using (var bitmap = (Bitmap)Image.FromFile(imageFilePath))//load the image file { using(Graphics graphics = Graphics.FromImage(bitmap)) { using (Font arialFont = new Font("Arial", 10)) { graphics.DrawString(firstText, arialFont, Brushes.Blue, firstLocation); graphics.DrawString(secondText, arialFont, Brushes.Red, secondLocation); } } newBitmap = new Bitmap(bitmap); } newBitmap.Save(imageFilePath);//save the image file newBitmap.Dispose();
如果有人在使用此代码行时遇到问题:
using(Graphics graphics = Graphics.FromImage(bitmap))
解决方案是:
Bitmap bitmap = (Bitmap)**System.Drawing.Image.FromFile**(@"C:\Documents and Settings\", true);