Mr *_*emi 27 c# text image draw
我有以下问题.我想在位图图像中制作一些图形,如债券形式
我可以在图像中写一个文字,
但我会在不同的位置写更多的文字
Bitmap a = new Bitmap(@"path\picture.bmp");
using(Graphics g = Graphics.FromImage(a))
{
g.DrawString(....); // requires font, brush etc
}
Run Code Online (Sandbox Code Playgroud)
如何编写文本并保存并在保存的图像中写入另一个文本
Jal*_*aid 69
要绘制多个字符串,请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
Run Code Online (Sandbox Code Playgroud)
编辑: "我添加一个加载并保存代码".
您可以随时打开位图文件Image.FromFile
,并使用上面的代码在其上绘制新文本.然后保存图像文件bitmap.Save
这是调用 的示例Graphics.DrawString
,取自此处:
g.DrawString("My\nText", new Font("Tahoma", 40), Brushes.White, new PointF(0, 0));
Run Code Online (Sandbox Code Playgroud)
它显然依赖于安装了一种名为的字体Tahoma
。
该Brushes
课程有许多内置画笔。
另请参阅 MSDN 页面Graphics.DrawString
。
为了保存对同一文件的更改,我必须结合Jalal Said的回答和NSGaga对这个问题的回答。您需要在旧的基础上创建一个新的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();
Run Code Online (Sandbox Code Playgroud)