OriginalGriff was a bit faster than me.. but I have a suggestion on how to otherwise improve your code: Instead of explicitly disposing objects, use
using
-blocks. It will ensure that your object is being disposed "no matter what" when leaving the scope and it improves readibility (well, most people think so at least). Also, by re-assigning a second Graphics-object to your variable
graphics
you're not disposing the first one.
private Bitmap CreateBarcode(string text)
{
if (String.IsNullOrEmpty(text))
throw new ArgumentException(nameof(text) + " may not be null or empty.");
Bitmap barcode;
using (Font font = new Font("Free Font", 60, FontStyle.Regular, GraphicsUnit.Point))
{
using (Bitmap dummyBitmap = new Bitmap(1, 1))
using (Graphics graphic = Graphics.FromImage(dummyBitmap))
{
SizeF size = graphic.MeasureString(text, font);
barcode = new Bitmap(dummyBitmap, size.ToSize());
}
using (Graphics graphic = Graphics.FromImage(barcode))
{
graphic.Clear(Color.White);
graphic.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
graphic.DrawString(text, font, new SolidBrush(Color.Black), 0, 0);
graphic.Flush();
}
}
return barcode;
}