Creating barcode from font Free 3 of 9 - c#

This is my code to create barcode image:
class Program
{
static void Main(string[] args)
{
CreateBarcode("The quick brown fox jumps over the lazy dog".ToUpper());
}
private static void CreateBarcode(string code)
{
var myBitmap = new Bitmap(500, 50);
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 = Encoder.Quality;
var myEncoderParameters = new EncoderParameters(1);
var myEncoderParameter = new EncoderParameter(myEncoder, 100L);
myEncoderParameters.Param[0] = myEncoderParameter;
//MemoryStream memoryStrem = new
myBitmap.Save(#"d:\Barcode.jpg", jgpEncoder, myEncoderParameters);
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
var codecs = ImageCodecInfo.GetImageDecoders();
foreach (var codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
}
This works fine however, this line: g.DrawString(code, new Font("Free 3 of 9", 50), Brushes.Black, new RectangleF(0, 0, 500, 50), strFormat);
as you can see the width here is 500. Now if I specify a big paragraph of text I fear that 500 would not be enough. Is there any way to make this width dynamic based on content?

Its too old to answer, Still am posting as it may help some one. We can create graphics object with a dummy bitmap and try find the length of font, after than re-initialize the bitmap as well as graphics object.
var myBitmap = new Bitmap(1, 1);
Font threeOfNine = new Font("Free 3 of 9", 60, FontStyle.Regular, GraphicsUnit.Point);
var g = Graphics.FromImage(myBitmap);
SizeF dataSize = g.MeasureString(code, threeOfNine);
myBitmap = new Bitmap(myBitmap, dataSize.ToSize());
g = Graphics.FromImage(myBitmap);

Related

Printing Multiple Pages C#

I'm trying to print some text data using an event handler, and then print a PDF on the second page.
I'm using pdfium viwer to do this and it works individually. But I'm struggling to combine them.
I need to get the two to print as 2 pages of the same print document, as I want to use a duplex printer to print the pdf on the back. I don't just want to send two individual pages.
Sample code:
To Print PDF:
private void button1_Click(object sender, EventArgs e)
{
string filena = #textBox1.Text;
PrintPDF("M2020", "A4", filena, 1);
}
public bool PrintPDF(string printer, string paperName, string filename, int copies)
{
try
{
// Create the printer settings for our printer
var printerSettings = new PrinterSettings
{
PrinterName = printer,
Copies = (short)copies,
};
// Create our page settings for the paper size selected
var pageSettings = new PageSettings(printerSettings)
{
Margins = new Margins(0, 0, 0, 0),
};
foreach (PaperSize paperSize in printerSettings.PaperSizes)
{
if (paperSize.PaperName == paperName)
{
pageSettings.PaperSize = paperSize;
break;
}
}
// Now print the PDF document
using (var document = PdfDocument.Load(filename))
{
using (var printDocument = document.CreatePrintDocument())
{
printDocument.PrinterSettings = printerSettings;
printDocument.DefaultPageSettings = pageSettings;
printDocument.PrintController = new StandardPrintController();
printDocument.Print();
}
}
return true;
}
catch
{
return false;
}
}
And my original code to print a QR code:
private void Doc_PrintPage(object sender, PrintPageEventArgs e)
{
string s2 = "Modified by: ";
string s6 = "Author: " + author;
string s4 = "Created: " + drawdate;
QRCodeGenerator qrGenerator1 = new QRCodeGenerator();
QRCodeData qrCodeDataPrint = qrGenerator1.CreateQrCode(qrcodedata, QRCodeGenerator.ECCLevel.Q, false, false);
Bitmap qrCodeImagePrint = (new QRCode(qrCodeDataPrint)).GetGraphic(20);
Bitmap bmimg = new Bitmap(this.pictureBox2.Width, this.pictureBox2.Height);
this.pictureBox2.DrawToBitmap(bmimg, new Rectangle(0, 0, this.pictureBox2.Width, this.pictureBox2.Height));
System.Drawing.Font f1 = new System.Drawing.Font("Arial", 5f, FontStyle.Bold, GraphicsUnit.Millimeter);
System.Drawing.Font f2 = new System.Drawing.Font("Arial", 2f, GraphicsUnit.Millimeter);
System.Drawing.Font f3 = new System.Drawing.Font("Arial", 3f, GraphicsUnit.Millimeter);
System.Drawing.Font barc = new System.Drawing.Font("Code39Azalea", 36f, GraphicsUnit.Point);
e.Graphics.PageUnit = GraphicsUnit.Millimeter;
Pen blackPen = new Pen(Color.Black, 1f);
Rectangle rect = new Rectangle(165, 35, 30, 30);
Rectangle qrcodetest = new Rectangle(170, 40, 25, 25);
Rectangle btmimg = new Rectangle(60, 140, 120, 120);
Rectangle combox = new Rectangle(20, 145, 160, 40);
e.Graphics.DrawImage(qrCodeImagePrint, qrcodetest);
e.Graphics.DrawRectangle(blackPen, qrcodetest);
e.Graphics.DrawString(this.procreq, f1, Brushes.Black, new Point(50, 5));
e.Graphics.DrawString(s1, f1, Brushes.Black, new Point(150, 70));
e.Graphics.DrawString(s1z, f2, Brushes.Black, new Point(150, 75));
e.Graphics.DrawString(qrissuedby, f2, Brushes.Black, new Point(20, 264));
e.Graphics.DrawString(s6, f2, Brushes.Black, new Point(20, 267));
e.Graphics.DrawString(s4, f2, Brushes.Black, new Point(20, 270));
e.Graphics.DrawString(s2, f2, Brushes.Black, new Point(20, 273));
e.Graphics.DrawString(s3, f2, Brushes.Black, new Point(20, 276));
e.Graphics.DrawString(s5, f2, Brushes.Black, new Point(20, 279));
e.Graphics.DrawString(this.notebox.Text, f3, Brushes.Black, combox);
e.Graphics.DrawImage(bitmap1, btmimg);
bmimg.Dispose();
bitmap1.Dispose();
}
Any help would be much appreciated!
Thanks
Andrew
Ok, think i was going about that in completely the wrong way. What I eventually did was use the pdfium viewer to render the pdf as a bitmap, and then printed that as the second page.
e.Graphics.PageUnit = GraphicsUnit.Millimeter;
Pen blackPen = new Pen(Color.Black, 1f);
int actualwidth = (int)(e.Graphics.DpiX * 210 / 25.4f);
int actualHeight = (int)(e.Graphics.DpiY * 297 / 25.4f);
using (var pdfDocument = PdfiumViewer.PdfDocument.Load(#textBox1.Text))
{
var bitmapImage = pdfDocument.Render(0, actualwidth, actualHeight, false);
pictureBox1.Image = bitmapImage;
pictureBox1.Image.RotateFlip((RotateFlipType.Rotate90FlipNone));
}
if (pgnum == 1)
{
Debug.WriteLine("firing first page " + pgnum);
Rectangle qrcodetest = new Rectangle(170, 40, 25, 25);
e.Graphics.DrawRectangle(blackPen, qrcodetest);
e.HasMorePages = true;
pgnum++;
Debug.WriteLine(pgnum);
}
else
{
Debug.WriteLine("firing second page " + pgnum);
GraphicsUnit units = GraphicsUnit.Millimeter;
Rectangle srcRect = new Rectangle(0, 0, 199, 281);
//e.Graphics.Q
e.Graphics.Clear(Color.White);
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
e.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
e.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
e.Graphics.DrawImage(pictureBox1.Image, srcRect);
e.HasMorePages = false;
}
This does work.... but the printed version of the PDF is very poor quality. I've tried using interpolation etc.... but doesn't seem to make any difference, so not sure i'm putting it in the right place?
Also, i've tried using the bitmap variable rather than the picturebox image, but it seems to generate the same result. The PDF prints much better.
Thanks
Andrew

Blob doesn`t match tracking object

hi,
I need to use color tracking.
The blob does not match my target object when I run my code in surface pro 4.
but the code is correct when I test it on my Acer.
anyone knows that why?
public void forobject(Bitmap image)//put setted color value into image1
{
BlobCounter blobCounter = new BlobCounter();
blobCounter.MinWidth = 5;
blobCounter.MinHeight = 5;
blobCounter.FilterBlobs = true;
blobCounter.ObjectsOrder = ObjectsOrder.Size;
//Grayscale griFiltre = new Grayscale(0.2125, 0.7154, 0.0721);
//Grayscale griFiltre = new Grayscale(0.2, 0.2, 0.2);
//Bitmap griImage = griFiltre.Apply(image);
BitmapData objectsData = image.LockBits(new Rectangle(0, 0, image.Width/2, image.Height/2), ImageLockMode.ReadOnly, image.PixelFormat);
// grayscaling
Grayscale grayscaleFilter = new Grayscale(0.2125, 0.7154, 0.0721);
UnmanagedImage grayImage = grayscaleFilter.Apply(new UnmanagedImage(objectsData));
// unlock image
image.UnlockBits(objectsData);
blobCounter.ProcessImage(image);
Rectangle[] rects = blobCounter.GetObjectsRectangles();
Blob[] blobs = blobCounter.GetObjectsInformation();
pictureBox_tracking.Image = image;//????
if (rdiobtn_singletracking.Checked)
{
// Single Tracking--------
foreach (Rectangle recs in rects)
{
if (rects.Length > 0)
{
Rectangle objectRect = rects[0];
//Graphics g = Graphics.FromImage(image);
Graphics g = pictureBox_real.CreateGraphics();
using (Pen pen = new Pen(Color.FromArgb(252, 3, 26), 2))
{
g.DrawRectangle(pen, objectRect);
}
//Drawn by the rectangle coordinates is taken away.
//int objectX = objectRect.X; //+ (objectRect.Width / 2);
//int objectY = objectRect.Y; //+ (objectRect.Height / 2);
x = objectRect.X;
y = objectRect.Y;
w = objectRect.Width;
h = objectRect.Height;
// g.DrawString(objectX.ToString() + "X" + objectY.ToString(), new Font("Arial", 12), Brushes.Red, new System.Drawing.Point(250, 1));
g.Dispose();
}

generating qr-code image [duplicate]

This question already has answers here:
Free c# QR-Code generator [closed]
(4 answers)
Closed 7 years ago.
After using this lines of code bellow
private void button1_Click(object sender, EventArgs e)
{
string barcode = textBox1.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 white = new SolidBrush(Color.White);
SolidBrush black = new SolidBrush(Color.Black);
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);
pictureBox1.Image = bitmap;
pictureBox1.Height = bitmap.Height;
pictureBox1.Width = bitmap.Width;
}
}
i was able to generate this output image barcode
i want to generate a bar code that output like the image bellow how can i achieve this
You can do it like this
private System.Drawing.Image GenerateQRCode(string content, int size)
{
QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.H);
QrCode qrCode;
encoder.TryEncode(content, out qrCode);
GraphicsRenderer gRenderer = new GraphicsRenderer(new FixedModuleSize(4, QuietZoneModules.Two), System.Drawing.Brushes.Black, System.Drawing.Brushes.White);
//Graphics g = gRenderer.Draw(qrCode.Matrix);
MemoryStream ms = new MemoryStream();
gRenderer.WriteToStream(qrCode.Matrix, ImageFormat.Bmp, ms);
var imageTemp = new Bitmap(ms);
var image = new Bitmap(imageTemp, new System.Drawing.Size(new System.Drawing.Point(size, size)));
//image.Save("file.bmp", ImageFormat.Bmp);
return (System.Drawing.Image)image;
}
Implementaion
string barcode = textBox1.Text;
codeImage = GenerateQRCode(barcode, 120);
// you can make a smaller image as per your need
rect = new System.Drawing.Rectangle(1080, 530, codeImage.Width, codeImage.Height);
using (Graphics g = Graphics.FromImage(picEdit))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawImage(codeImage, rect);
}
Do not forget to add
using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
from GitHub: QrCode.Net

Bitmap graphics: when saving on disk no drawed strings - works when memorystream

I am creating a PNG picture, using the Bitmap object, using Drawing.Graphics . I create a Bitmap, insert a background image and draw some strings.
Now, when I save the image on the disk, the files does not have my strings!
I am doing this in ASP.NET MVC, where this is my controllers signature:
[AcceptVerbs(HttpVerbs.Get)]
public string GetNewsletterPicture(string headline, string tagline)
When I don't save the image on the disk and instead returns a FileStreamResult from a MemoryStream, the image looks perfectly.
So there is some problem that when I save the image to the disk, the strings are "forgotten" somehow.
Any ideas?
My code:
ColorConverter converter = new ColorConverter();
Color textColor = (Color)converter.ConvertFromString("#FF58595B");
int width = 598;
int height = 77;
int offSet = 40;
int shadowOffset = 1;
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.LightGray);
Image backgroundImg = new Bitmap(Server.MapPath("~/Static/Images/bgimg.png"));
g.DrawImage(backgroundImg,0,0);
StringFormat sf= new StringFormat();
sf.Alignment = StringAlignment.Center;
var rectangleTop = new RectangleF(0, 0, width, height);
var rectangleTopShadowHack = new RectangleF(shadowOffset, shadowOffset, width + shadowOffset, height + shadowOffset);
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// only show headline and center it
if (!string.IsNullOrEmpty(tagline))
{
var rectangleBottomShadowHack = new RectangleF(shadowOffset, offSet + shadowOffset, width + shadowOffset, height - offSet + shadowOffset);
var rectangleBottom = new RectangleF(0, offSet, width, height - offSet);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(Color.White), rectangleBottomShadowHack, sf);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(textColor), rectangleBottom, sf);
}
else
{
sf.LineAlignment = StringAlignment.Center;
}
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(Color.White), rectangleTopShadowHack, sf);
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(textColor), rectangleTop, sf);
g.Save();
var fileName = Guid.NewGuid().ToString() + ".png";
var path = Server.MapPath("~/Static/Previews/" + fileName);
bmp.Save(path, ImageFormat.Png);
return fileName;
If in doubt, it is the g.DrawString which is not being saved on the picture.
NEW atttempt (still not working):
[AcceptVerbs(HttpVerbs.Get)]
public string GetNewsletterPicture(string headline, string tagline)
{
ColorConverter converter = new ColorConverter();
Color textColor = (Color)converter.ConvertFromString("#FF58595B");
int width = 598;
int height = 77;
int offSet = 40;
int shadowOffset = 1;
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.LightGray);
Image backgroundImg = new Bitmap(Server.MapPath("~/Static/Images/bgimg.png"));
g.DrawImage(backgroundImg,0,0);
StringFormat sf= new StringFormat();
sf.Alignment = StringAlignment.Center;
var rectangleTop = new RectangleF(0, 0, width, height);
var rectangleTopShadowHack = new RectangleF(shadowOffset, shadowOffset, width + shadowOffset, height + shadowOffset);
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// only show headline and center it
if (!string.IsNullOrEmpty(tagline))
{
var rectangleBottomShadowHack = new RectangleF(shadowOffset, offSet + shadowOffset, width + shadowOffset, height - offSet + shadowOffset);
var rectangleBottom = new RectangleF(0, offSet, width, height - offSet);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(Color.White), rectangleBottomShadowHack, sf);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(textColor), rectangleBottom, sf);
}
else
{
sf.LineAlignment = StringAlignment.Center;
}
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(Color.White), rectangleTopShadowHack, sf);
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(textColor), rectangleTop, sf);
g.Flush(FlushIntention.Sync);
}
var fileName = Guid.NewGuid().ToString() + ".png";
var path = Server.MapPath("~/Static/Previews/" + fileName);
bmp.Save(path, ImageFormat.Png);
return fileName;
//MemoryStream stm = new MemoryStream();
//bmp.Save(stm,System.Drawing.Imaging.ImageFormat.Png);
//stm.Position = 0;
//return new FileStreamResult(stm, "image/png");
}
I can't tell for sure, but it looks like you might be confusing g.Save() with g.Flush().
You need to call g.Flush(FlushIntention.Sync) instead of g.Save(). You should probably also call bmp.Save() outside of the using block:
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
//...
g.Flush(FlushIntention.Sync);
}
var fileName = Guid.NewGuid().ToString() + ".png";
var path = Server.MapPath("~/Static/Previews/" + fileName);
bmp.Save(path, ImageFormat.Png)
Save() is used to save the current graphics state so that you can modify it and then restore it later.:
GraphicsState oldState = g.Save();
// Make some changes to the graphics state...
g.Restore(oldState);
Flush() on the other hand, is used to force the graphics object to complete any pending operations. By passing FlushIntention.Sync as a parameter, Flush() won't return until the flushing is complete.

Generate transparent PNG c#

I have the function below to generate a sample logo. What I want to do is to return a transparent png or gif instead of a white background.
How can I do that?
private Bitmap CreateLogo(string subdomain)
{
Bitmap objBmpImage = new Bitmap(1, 1);
int intWidth = 0;
int intHeight = 0;
Font objFont = new Font(
"Arial",
13,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Pixel);
Graphics objGraphics = Graphics.FromImage(objBmpImage);
intWidth = (int)objGraphics.MeasureString(subdomain, objFont).Width;
intHeight = (int)objGraphics.MeasureString(subdomain, objFont).Height;
objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));
objGraphics = Graphics.FromImage(objBmpImage);
objGraphics.Clear(Color.White);
objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
objGraphics.DrawString(
subdomain, objFont,
new SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);
objGraphics.Flush();
return (objBmpImage);
}
Here is the end result:
context.Response.ContentType = "image/png";
using (MemoryStream memStream = new MemoryStream())
{
CreateLogo(_subdname).Save(memStream, ImageFormat.Png);
memStream.WriteTo(context.Response.OutputStream);
}
In the CreateLogo function:
objGraphics.Clear(Color.White) was changed to objGraphics.Clear(Color.Transparent)
new SolidBrush(Color.FromArgb(102, 102, 102)) changed to new SolidBrush(Color.FromArgb(255, 255, 255))
You can do something like this:
Bitmap bmp = new Bitmap(300, 300);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.Transparent);
g.FillRectangle(Brushes.Red, 100, 100, 100, 100);
g.Flush();
bmp.Save("test.png", System.Drawing.Imaging.ImageFormat.Png);
Take a look at Can you make an alpha transparent PNG with C#?

Categories