FAQ TBarCode .NET
How Can I Control the Bitmap Transparency
How Can I Control the Bitmap Transparency
When creating a barcode in bitmap format, there are two possibilities to adjust the background:
- IsBackgroundTransparent = TRUE → When drawing the barcode (DC, Graphics, Bitmap) only the bars are drawn, the rest remains free
- IsBackgroundTransparent = FALSE → When drawing the barcode (DC, Graphics, Bitmap) the background is filled first, then the bars are drawn
Recommended Workflow
If you want to create a bitmap barcode with a transparent background, you have to set the transparency color separately. To do this, first draw into a bitmap, set the transparency and then save it. Try one of the two following options:
Option #1
Draw the barcode with a white background:
- IsBackgroundTransparent := FALSE (→ the barcode library draws a white background)
Specify the transparency color:
- bitmap.MakeTransparent( Color.White ); //make be background transparent - this will be an index (rather than an alpha) transparency
Sample code in C#:
Barcode BC = new Barcode();
int width = 300;
int height = 150;
BC.BarcodeType = BarcodeType.Code128;
BC.Data = "12345";
BC.IsBackgroundTransparent = false;
BC.BoundingRectangle = new Rectangle(0, 0, width, height); // Pixel
Bitmap bitmap = new Bitmap(width, height);
Graphics gfx = Graphics.FromImage(bitmap);
BC.Draw(gfx);
bitmap.MakeTransparent(Color.White);
bitmap.Save("c:\\temp\\test1a.png", System.Drawing.Imaging.ImageFormat.Png);
Variant without graphics object:
Barcode BC = new Barcode();
int width = 300;
int height = 150;
BC.BarcodeType = BarcodeType.Code128;
BC.Data = "12345";
BC.IsBackgroundTransparent = false;
BC.BoundingRectangle = new Rectangle(0, 0, width, height); // Pixel
Bitmap bitmap = BC.DrawBitmap();
bitmap.MakeTransparent(Color.White);
bitmap.Save("c:\\temp\\test1b.png", System.Drawing.Imaging.ImageFormat.Png);
Option #2
Draw the barcode without background:
- IsBackgroundTransparent := FALSE (→ the barcode library draws a white background)
Fill background with transparency:
- gfx.Clear(Color.Transparent);
Sample Code in C#:
Barcode BC = new Barcode();
int width = 300;
int height = 150;
BC.BarcodeType = BarcodeType.Code128;
BC.Data = "12345";
BC.IsBackgroundTransparent = true;
BC.BoundingRectangle = new Rectangle(0, 0, width, height); // Pixel
Bitmap bitmap = new Bitmap(width, height);
Graphics gfx = Graphics.FromImage(bitmap);
gfx.Clear(Color.Transparent);
gfx.Flush();
BC.Draw(gfx);
bitmap.Save("c:\\temp\\test2.png", System.Drawing.Imaging.ImageFormat.Png);
Notes
- Please note that the example barcode is not pixel-optimized.
- We recommend to use PNG images.
- Further information about transparency can be found here.