Hello:
I need to write a C# program to create an image from some text, and I have to center the text in the image.
Since I am using Visual Studio 2019 on Windows 10, and I have to use .NET 5.0, so I created one C# WinForms App, and add the following code:
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Windows.Forms;
namespace CenterTextInImage
{
public partial class Form1 : Form
{
private PictureBox pictureBox1 = new ();
private Button button1 = new();
public Form1()
{
InitializeComponent();
pictureBox1.Location = new Point(12, 30);
pictureBox1.Name = "pictureBox1";
pictureBox1.Size = new Size(768, 268);
pictureBox1.TabIndex = 1;
pictureBox1.TabStop = false;
Controls.Add(pictureBox1);
button1.Location = new System.Drawing.Point(363, 364);
button1.Name = "button1";
button1.Size = new System.Drawing.Size(75, 23);
button1.TabIndex = 0;
button1.Text = "SaveImage";
button1.UseVisualStyleBackColor = true;
button1.Click += new System.EventHandler(button1_Click);
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
string text1 = "Test for center text in the image";
using Font font12 = new("Arial", 12, FontStyle.Bold, GraphicsUnit.Point);
g.Clear(Color.FromKnownColor(KnownColor.White));
Rectangle rect1 = new(0, 0, B20_Image_Width, B20_Image_Height);
TextFormatFlags flags = TextFormatFlags.HorizontalCenter |
TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak;
TextRenderer.DrawText(e.Graphics, text1, font12, rect1, Color.Black, flags);
e.Graphics.DrawRectangle(Pens.Black, rect1);
}
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.Paint += new PaintEventHandler(pictureBox1_Paint);
}
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image.Save(@"C:\Images\Test1.png", ImageFormat.Png);
}
}
}
When I run this code, I can see the text is drawn in the center of the image. But I can't figure out how to save the image from the pictureBox1.
When I click on button1, I always got error:
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=AddText2ImageForm
When I debug my code, I can always see that the image of pictureBox1 is null.
How I can save the image from pictureBox1?
My IDE is: Visual Studio 2019 (version 16.10.4), and my OS is Windows 10 (Version 21H1)
Thanks,