I have a piece of code that generates the barcode image (using the Free 3 of 9 font); nevertheless, the picture size is defined ahead of time and I am wondering what can I do to adjust it to the required size?
private static Bitmap CreateBarcode(string code)
{
var myBitmap = new Bitmap(500, 50);
//var myBitmap = new Bitmap();
var g = Graphics.FromImage(myBitmap);
var jgpEncoder = GetEncoder(ImageFormat.Jpeg);
g.Clear(Color.White);
var strFormat = new StringFormat { Alignment = StringAlignment.Center };
g.DrawString(code, new Font("Free 3 of 9", 50), Brushes.Black, new RectangleF(0, 0, 500, 50), strFormat);
var myEncoder = System.Drawing.Imaging.Encoder.Quality;
var myEncoderParameters = new EncoderParameters(1);
var myEncoderParameter = new EncoderParameter(myEncoder, 100L);
myEncoderParameters.Param[0] = myEncoderParameter;
return myBitmap;
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
var codecs = ImageCodecInfo.GetImageDecoders();
foreach (var codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
I think you’re looking for the
Graphics.MeasureStringmethod. This will measure the size of the resulting image representation of the string you’re drawing, allowing you to calculate the size of your bitmap. If it doesn’t fit, grow the bitmap before drawing, or if it’s too small crop it. MSDN forMeasure String