I am generating a barcode as an image. The barcode consists of few different values, such as amount, length, width and m2. These numbers are displaying below the barcode as a summary of all user entries. Is there a way to either bold or underline the m2 (square meters) in the summary under the barcode? Please see below sample of what is needed:
Here's the code I use to generate the barcode:
private void generate_Click(object sender, EventArgs e)
{
String barcode = summary.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);
box4.Image = bitmap;
box4.Height = bitmap.Height;
box4.Width = bitmap.Width;
}
}
You can use the constructor of Font that accepts a font style (docs)
new System.Drawing.Font("IDAutomationHC39M", 20, FontStyle.Bold);
The problem comes in determining what part of the text should be bold which means you will have to split the text up at a certain point, and ascertain the offset of the bold text
Since the font you're using (IDAutomationHC39M), renders the bar code also, this won't work unless you find a different font that will allow you to render the bars separately to the text. This leaves you with a few options.
Separate fonts
Don't make the text you want to bold
Make it stand out in a different way, colour the text in a different colour that will make it stand out / draw a line under it / etc
If this was just text
You need to break the text up into 2 parts,
string barcode1; //the normal bit
string barcode2; //the bold/underlined bit
Font ofont = new System.Drawing.Font("IDAutomationHC39M", 20);
Font ofontBold = new System.Drawing.Font("IDAutomationHC39M", 20, FontStyle.Bold);
Then render text in 3 stages, measuring the offset of each previous part:
graphics.DrawString("*" + barcode1, ofont, black, point);
var point2 = new PointF(point.X + graphics.MeasureString("*" + barcode1, ofont).Width, point.Y);
graphics.DrawString(barcode2, ofontBold, black, point2);
var point3 = new PointF(point2.X + graphics.MeasureString(barcode2, ofontBold).Width, point2.Y);
graphics.DrawString("*", ofont, black, point3);
However the font includes the lines
So I think the best you can do is to draw an underline using the same string measuring techniques:
string barcode1; //the normal bit
string barcode2; //the underlined bit
var lineStartX = point.X + graphics.MeasureString("*" + barcode1, ofont).Width;
var lineWidth = graphics.MeasureString(barcode2).Width;
Related
I have some C# code that adds a simple text overlay with a border and semi-transparent background to an image. It works great, but I'm trying to get an equivalent result using Magick.NET. (The straight C# code drops the XMP tags from the original image, and I haven't found a way to deal with that.) Magick.NET handles the XMP tags well, but I'm having trouble replicating the original output.
Original code follows:
using (Image i = Image.FromStream(stream))
{
int width = i.Width;
int height = i.Height;
using (Graphics graphics = Graphics.FromImage(i))
{
string measureString = "my string";
Size stringSize = graphics.MeasureString(measureString, stringFont).ToSize();
Point drawLocation = new Point(width - stringSize.Width - 15, height - stringSize.Height - 15);
Rectangle rect = new Rectangle(drawLocation.X, drawLocation.Y, stringSize.Width, stringSize.Height);
graphics.DrawRectangle(blackPen, rect);
graphics.FillRectangle(fillBrush, rect);
graphics.DrawString(measureString, stringFont, Brushes.Yellow, drawLocation);
}
i.Save(outputFolder + Path.GetFileName(imgFileName));
}
I cobbled this together based on the Magick.NET examples. This get close to what I'm looking for, but adding the border removes the transparency value, and I'm left with a dark gray background, instead of the transparency.
var settings = new MagickReadSettings{
Font = "Calibri",
FillColor=MagickColors.Yellow,
StrokeColor=MagickColors.Black,
TextGravity = Gravity.Center,
BackgroundColor = new MagickColor("#66666699"),
BorderColor = MagickColors.Black,
Height = 250, // height of text box
Width = 680 // width of text box
};
using (var image = new MagickImage(inputFile))
{
using (var caption = new MagickImage($"caption:{myString}", settings))
{
//adding this border removes transparency
// caption.BorderColor = MagickColors.Black;
// caption.Border(1);
image.Composite(caption, Gravity.Southeast, CompositeOperator.Over);
image.Write(outputFile);
}
}
In command line ImageMagick, this seems to work for me in that the background color is transparent gray. The following the result may be what you want:
convert -font ubuntu -fill yellow -stroke black -gravity center -background "#66666699" -bordercolor black -size 250x680 caption:"This Is Some Text" result.png
Note: I used -background, not -backgroundcolor. Also BorderColor is not the color for the outline of the text. That is the stroke. You have not used BorderColor, since you have not specified the Border amount (as in -border in command line), which would outline the image rectangle and not the text.
Due to time constraints with my project, I took a slightly different path to make this work. I wound up creating the transparent overlay using my original .NET drawing code, and passing that as a memory stream to Magick.NET to handle the merge.
Workaround:
string measureString = "build custom string here";
using (var tmpStreamImg = new MemoryStream())
{
// Call custom function to get length of my string
System.Drawing.Size stringSize = MeasureString(measureString, stringFont).ToSize();
Rectangle rect = new Rectangle(0, 0, stringSize.Width, stringSize.Height);
using (Bitmap overlay = new Bitmap(rect.Width, rect.Height))
{
overlay.SetResolution(350, 350);
using (Graphics overlayGraphic = Graphics.FromImage(overlay))
{
overlayGraphic.DrawRectangle(blackPen, rect);
overlayGraphic.FillRectangle(fillBrush, rect);
overlayGraphic.DrawString(measureString, stringFont, Brushes.Yellow, 3, 3);
}
overlay.Save(tmpStreamImg, ImageFormat.Png);
}
tmpStreamImg.Position= 0;
using (var originalImage = new MagickImage(imgFileName))
{
using (var overlayImage = new MagickImage(tmpStreamImg))
{
originalImage.Composite(overlayImage, Gravity.Southeast, CompositeOperator.Over);
originalImage.Write(outputFolder + Path.GetFileName(imgFileName));
}
}
}
I have a custom control that may have user customizable Font in future (the zoom is already implemented). I must fill a rectangle under two digits that form a base-10 number. I have different colors for zero, one or both of the digits.
With the font {Name = Microsoft Sans Serif Size=16} and the following Graphics.MeasureString method calls:
g.MeasureString("00", Font);
g.MeasureString("0", Font);
I get:
The size of "00" is {Width = 31.5486088 Height = 26.8124962}
The size of "0" is {Width = 19.3298588 Height = 26.8124962}
The width of "0" is a lot bigger that half of the width of "00".
I know of the methods Graphics.MeasureString, it has many overloads, and I also know of the StringFormat class. How can I correctly compute the width of the '0' char?
Because the font will be user-customizable, I do not want to solve the problem using a monospace font.
If I use the following calls:
g.MeasureString("00", Font, 999, StringFormat.GenericTypographic);
g.MeasureString("0", Font, 999, StringFormat.GenericTypographic);
The width of "0" seems to be half of the width of "00", but the digits overlap when drawn with a smaller font size:
Update: In the OnPaint method of an UserControl I have this code:
Graphics g = e.Graphics;
int[] indices = { 0, 1 };
CharacterRange[] charRanges = new CharacterRange[indices.Length];
for (int chx = 0; chx < indices.Length; ++chx)
{
charRanges[chx] = new CharacterRange(indices[chx], 1);
}
StringFormat sf = new StringFormat(StringFormat.GenericDefault);
sf.SetMeasurableCharacterRanges(charRanges);
Region[] regions = e.Graphics.MeasureCharacterRanges("01", Font, e.ClipRectangle, sf);
RectangleF[] r = new RectangleF[regions.Length];
int i = 0;
foreach (Region rr in regions)
{
r[i] = rr.GetBounds(g);
g.DrawRectangle(Pens.Blue, r[i].X, r[i].Y, r[i].Width, r[i].Height);
++i;
}
g.DrawString("0", Font, Brushes.Black, r[0], sf);
g.DrawString("1", Font, Brushes.Black, r[1], sf);
The font is {Name = "Microsoft Sans Serif" Size=25}. When running the program, this is what is visible:
I want to make the digits centered in the blue rectangles. The rectangles must be as big as possible in the UserControl but also leaving space for a percent of the Height of the UserControl. The Font should adapt to the rectangles.
Small adjustments are required to make this work as intended:
TextRenderingHint.ClearTypeGridFit gives a better result when rendering the Text.
It's more precise and works well with the grid-fitting nature of Graphics.DrawString.
See the notes you can find in the answer linked below for more informations on this matter.
StringFormat alignment in both horizontal and vertical dimensions.
A modified method that allows to draw strings of any length.
If the string is larger than the container, it will be wrapped, with the current settings.
Irrelevant: Brush and Pen are declared outside the Paint event, to allow their re-definition when required.
Different implementations of MeasureCharacterRanges here:
How to highlight wrapped text in a control
About Graphics.DrawString and TextRenderingHint.ClearTypeGridFit:
Drawing a Long String on to a Bitmap results in Drawing Issues
Font 48em:
Font 16em:
Font 9em:
Pen pen = new Pen(Color.LightGreen, 1);
Brush brush = new SolidBrush(Color.White);
string sourceDigits = "010011001";
private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
CharacterRange[] charRanges = new CharacterRange[sourceDigits.Length];
for (int chx = 0; chx < sourceDigits.Length; ++chx) {
charRanges[chx] = new CharacterRange(chx, 1);
}
using (StringFormat sf = new StringFormat())
{
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
sf.SetMeasurableCharacterRanges(charRanges);
Region[] regions = e.Graphics.MeasureCharacterRanges(sourceDigits, Font, e.ClipRectangle, sf);
for (int i = 0; i < regions.Length; i++) {
RectangleF rect = regions[i].GetBounds(e.Graphics);
e.Graphics.DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height);
e.Graphics.DrawString(char.ToString(sourceDigits[i]), Font, brush, rect, sf);
}
}
}
In my application, I generate a Bitmap with a variable string.
Here is my function:
public void Image(String text, String font, int size)
{
Font font = new Font(font, size);
float res = ((font.SizeInPoints * text.Length) / 72) * 96;
using (Bitmap img = new Bitmap((int)res, font.Height))
{
Graphics g = Graphics.FromImage(img);
SolidBrush drawBrush = new SolidBrush(Color.Black);
g.DrawString(text, font, drawBrush, 1, 0);
String directory = AppDomain.CurrentDomain.BaseDirectory + "Content\\Images\\Signature\\";
string outputFileName = directory + "sign.png";
img.Save(outputFileName, ImageFormat.Png);
}
}
I would like the width of the image to match perfectly the width of the string printed in that bitmap.
As you can see, I tried to calculate the width with point size of the font.
The problem is that each letter printed has a different width so I can not get the size before creating the Bitmap.
Plus, I don't even know how to retrieve the actual size of the printed string...
Does anyone have an idea?
Use the Graphics.MeasureString function. It takes a string and a font, and returns the size of the rendered text as a SizeF. There are also additional overloads that can take formatting information, and one that takes a SizeF representing the maximum width for wrapping.
Details can be found here: https://msdn.microsoft.com/en-us/library/6xe5hazb(v=vs.110).aspx
// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);
// Set maximum layout size.
SizeF layoutSize = new SizeF(100.0F, 200.0F);
// Set string format.
StringFormat newStringFormat = new StringFormat();
newStringFormat.FormatFlags = StringFormatFlags.DirectionVertical;
// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont, layoutSize, newStringFormat);
// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);
// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0,
Is there any open source library for drawing text to image in C#? I have been strugling with TextRenderer and graphics.DrawString() whole day but I never got close to getting decent results, I tried every combination of Smoothing, Interpolation, TextRenderHint but quality is always semi-decent.
Here are some images and that is best I achived:
How it needs to look like:
This really looks good but with some strings seems like character spacing is wrong with some letters and the string leans.
Settings are:
objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
objGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.GammaCorrected;
objGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
objGraphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;
objGraphics.TextContrast = 0;
Format is Png and background is transparent, method is TextRenderer.Drawtext(). Seems like thickness of text is wrong, I assume it's something wrong with smoothing, when I try to bold text it stays almost the same, but only with font size of ~10px.
Here's what I use to add a Copyright watermark to photos uploaded to my website:
//Add Watermark to photo.
private System.Drawing.Image CreateWatermark(System.Drawing.Image imgPhoto, string Copyright)
{
Graphics g = Graphics.FromImage(imgPhoto);
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
foreach (PropertyItem pItem in imgPhoto.PropertyItems)
{
imgPhoto.SetPropertyItem(pItem);
}
int phWidth = imgPhoto.Width;
int phHeight = imgPhoto.Height;
//create a Bitmap the Size of the original photograph
Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
//load the Bitmap into a Graphics object
Graphics grPhoto = Graphics.FromImage(bmPhoto);
//------------------------------------------------------------
//Step #1 - Insert Copyright message
//------------------------------------------------------------
//Set the rendering quality for this Graphics object
grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
//Draws the photo Image object at original size to the graphics object.
grPhoto.DrawImage(
imgPhoto, // Photo Image object
new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
0, // x-coordinate of the portion of the source image to draw.
0, // y-coordinate of the portion of the source image to draw.
phWidth, // Width of the portion of the source image to draw.
phHeight, // Height of the portion of the source image to draw.
GraphicsUnit.Pixel); // Units of measure
//-------------------------------------------------------
//to maximize the size of the Copyright message we will
//test multiple Font sizes to determine the largest posible
//font we can use for the width of the Photograph
//define an array of point sizes you would like to consider as possiblities
//-------------------------------------------------------
int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };
Font crFont = null;
SizeF crSize = new SizeF();
//Loop through the defined sizes checking the length of the Copyright string
//If its length in pixles is less then the image width choose this Font size.
for (int i = 0; i < 7; i++)
{
//set a Font object to Arial (i)pt, Bold
crFont = new Font("arial", sizes[i], FontStyle.Bold);
//Measure the Copyright string in this Font
crSize = grPhoto.MeasureString(Copyright, crFont);
if ((ushort)crSize.Width < (ushort)phWidth)
break;
}
//Since all photographs will have varying heights, determine a
//position 5% from the bottom of the image
int yPixlesFromBottom = (int)(phHeight * .05);
//Now that we have a point size use the Copyrights string height
//to determine a y-coordinate to draw the string of the photograph
float yPosFromBottom = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2));
//Determine its x-coordinate by calculating the center of the width of the image
float xCenterOfImg = (phWidth / 2);
//Define the text layout by setting the text alignment to centered
StringFormat StrFormat = new StringFormat();
StrFormat.Alignment = StringAlignment.Near;
//define a Brush which is semi trasparent black (Alpha set to 153)
SolidBrush semiTransBrush2 = new SolidBrush(System.Drawing.Color.FromArgb(153, 0, 0, 0));
//Draw the Copyright string
grPhoto.DrawString(Copyright, //string of text
crFont, //font
semiTransBrush2, //Brush
new PointF(xCenterOfImg + 1, yPosFromBottom + 1), //Position
StrFormat);
//define a Brush which is semi trasparent white (Alpha set to 153)
SolidBrush semiTransBrush = new SolidBrush(System.Drawing.Color.FromArgb(153, 255, 255, 255));
//Draw the Copyright string a second time to create a shadow effect
//Make sure to move this text 1 pixel to the right and down 1 pixel
grPhoto.DrawString(Copyright, //string of text
crFont, //font
semiTransBrush, //Brush
new PointF(xCenterOfImg, yPosFromBottom), //Position
StrFormat); //Text alignment
imgPhoto = bmPhoto;
return imgPhoto;
}
Using System.Drawing classes in ASP.NET is not supported.
Specifically, if you use it, under load from multiple threads, you will experience exceptions like this one:
Win32Exception: The operation completed successfully
at MS.Win32.HwndWrapper..ctor(Int32 classStyle, Int32 style, Int32 exStyle, Int32 x, Int32 y, Int32 width, Int32 height, String name, IntPtr parent, HwndWrapperHook[] hooks)
at System.Windows.Media.MediaContextNotificationWindow..ctor(MediaContext ownerMediaContext)
at System.Windows.Media.MediaContext..ctor(Dispatcher dispatcher)
That said, we discovered that marshaling all drawing operations to a single STA thread seemed to avoid these issues.
UPDATE: It's been five years and we still have no problem with this approach.
I would like to apply a watermark to images.
At the moment, I am trying to use this code, but it's failing on different sized images:
public void AddWaterMark(string filePath, string watermarkText)
{
Image img = Image.FromFile(
MapPath(GlobalVariables.UploadPath + "/" + filePath));
Graphics gr = Graphics.FromImage(img);
Font font = new Font("Alial Black", 40);
Color color = Color.FromArgb(50, 241, 235, 105);
StringFormat stringFormat = new StringFormat
{
Alignment = StringAlignment.Near,
LineAlignment = StringAlignment.Near
};
gr.SmoothingMode = SmoothingMode.AntiAlias;
gr.DrawString(watermarkText, font, new SolidBrush(color),
new Point(20, img.Height - 60), stringFormat);
img.Save(MapPath(GlobalVariables.UploadPath + "/w_" + filePath));
}
Sometimes the font goes off the bottom. I want it to be text along the bottom of the image.
How do I ensure it doesn't go off the bottom?
Also, I want to enhance it slightly. I want to make a white, but transparent bar across the full length of the bottom of the image, and then write black text over it. Is this possible with drawing? So, a bar across the bottom of the image, maybe 60 pixels high, and in the middle of the 60px, I want text written (left aligned).
I am also finding the text moves arounf, depending on the file size
Here's an image that works:
http://www.listerhome.com/fulldisplay.aspx?imageid=100055
Bur sometimes, when I uploaded higher resolution images, I get this:
http://www.listerhome.com/fulldisplay.aspx?imageid=100060
You can use MeasureString function to calculate string size.
SizeF stringSize = gr.MeasureString(watermarkText, font, img.Width - 40);
gr.DrawString(watermarkText, font, new SolidBrush(color),
new RectangleF(20, img.Height - stringSize.Height, img.Width - 40, stringSize.Height),
stringFormat);