Reputation: 317
recently I have managed to get the app to work properly with no errors.
The problem is that it is supposed to generate a barcode with text underneath; what it does, it only generates an image with text - no barcode.
I am using the font IDAutomationHC39M. The app should convert the text into a barcode.
Please see the code below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String barcode = pole.Text;
Bitmap bitmap = new Bitmap(barcode.Length * 40, 150);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
Font ofont = new System.Drawing.Font("IDAutomationHC39M", 20);
PointF point = new PointF(2f, 2f);
SolidBrush black = new SolidBrush(Color.Black);
SolidBrush White = new SolidBrush(Color.White);
graphics.FillRectangle(White, 0, 0, bitmap.Width, bitmap.Height);
graphics.DrawString("*" + barcode + "*", ofont, black, point);
}
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(ms, ImageFormat.Png);
box.Image = bitmap;
box.Height = bitmap.Height;
box.Width = bitmap.Width;
}
}
private void pole_TextChanged(object sender, EventArgs e)
{
}
}
}
Upvotes: 1
Views: 534
Reputation: 54433
There are a few minor issues in you code, namely the leaking of GDI resources and the inexact measurement of the bitmap you create.
Here is a version that takes care of those issues:
String barcode = "*" + pole.Text + "*";
PointF point = new PointF(5f, 5f);
float fontHeight = 20f;
Bitmap bitmap = new Bitmap(123,123);
using (Font ofont = new System.Drawing.Font("IDAutomationHC39M", fontHeight))
{ // create a Graphics object to measure the barcode
using (Graphics graphics = Graphics.FromImage(bitmap))
{
Size sz = Size.Round(graphics.MeasureString( barcode, ofont));
bitmap = new Bitmap(sz.Width + 10, sz.Height + 10);
} // create a new one with the right size to work on
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.Clear(Color.White);
graphics.DrawString(barcode, ofont, Brushes.Black, point);
}
}
box.Image = bitmap;
box.ClientSize = bitmap.Size;
// bitmap.Save(fileName, ImageFormat.Png);
But your main problem most likely comes from using a not fully compatible Font. There are many free fonts out there and not all work equally well.
I found this font to work just fine but couldn't get this one to work directly, although one of my older programs, that enumerates the installed fonts, did work with it. But even the designer refused to use it, so it's not just the name..
Here is a sample :
Upvotes: 2