在我的应用程序中,我生成了一个条形码图像,该图像是根据用户使用 OpenFileDialog 上传的文件中的数据生成的。我的目标是允许用户在屏幕上查看条形码数据和图像本身,打印并使他们能够将两者保存为 PNG 图像(作为单个图像)。我使用过 PrintPageEventArgs、Graphics.DrawString、Graphics.DrawImage、2 个 PictureBox - 1 个是 Barcode 的值,另一个是实际图像。我可以在屏幕上和打印时显示相关信息(我使用 Get 和 Set 方法从文件中检索数据):
保存图片:
// Link to Form1 (Global Variable)
Form1 f1 = new Form1();
private void BtnSave_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "PNG Files (*.png) | *.png";
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.FileName = "Barcode";
ImageFormat format = ImageFormat.Png;
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
bm.Save(saveFileDialog1.FileName, format); // ADDED LINE
MessageBox.Show("Your image has been saved!");
}
}
显示
打印(预览)
保存
我正在努力解决的问题是保存条形码,到目前为止我只能保存图像而不能信息/值。因此,我想知道是否可以保存BOTH 条码值和图像以形成一个图像?我使用 Graphics.DrawString 作为值,使用 Graphics.DrawImage 作为实际条码。我已经研究过但找不到任何解决方案,尽管它看起来很简单,但显然不是......
已解决! (见接受的答案)
如果您遇到困难,我在这里发布了一些代码和解释: 请注意,这可能不是最好/有效的方式
Bitmap bm = new Bitmap(497, 140);
// This method is called from the Save Click event
private void Merge_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen blackPen = new Pen(Color.Transparent, 1);
StringFormat strF = new StringFormat();
using (g = Graphics.FromImage(bm)) // Using bitmap...
{
g.DrawImage(BarcodePic.Image, 0, 0); // Draw the BarcodePic to bm
string bb = f1.GetSetBarcode; // Getting value of Barcode
using (Font font = new Font("New Courier", 13, FontStyle.Regular)) // Declare font
{
strF.Alignment = StringAlignment.Center; // Set alignment of text
Rectangle value = new Rectangle(0, 120, 496, 20); // Position text
g.DrawString(bb.ToString(), font, Brushes.Black, value, strF); // Draw text
}
}
SaveFileDialog saveFileDialog1 = new SaveFileDialog(); // Create instance
saveFileDialog1.Filter = "PNG Files (*.png) | *.png";
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.FileName = "Barcode"; // Create default file name
ImageFormat format = ImageFormat.Png;
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
bm.Save(saveFileDialog1.FileName, format); // Save bm
MessageBox.Show("Your image has been saved!"); // Confirmation of action
}
}
希望这对处于我位置的其他人有所帮助:)
最佳答案
- 使用
new Bitmap(width, height)
创建一个Bitmap
- 使用
Graphics.FromImage
为其获取Graphics
- 使用
DrawImage
在此Graphics
上绘制条码 - 使用
DrawString
在此Graphics
上绘制文本 - 处理
图形
- 保存
位图
关于c# - 有没有办法将 Graphics.DrawString & Graphics.DrawImage 合并成一个图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20564150/