Save an image and text as one - c#

I am currently making an MVC project where the User will receive a Certificate which is displayed on the page. The Certificate is an image and then Text is used to overlap the image where the Users name and other information will be printed, using css to format the text to the correct part of the image.
As the image and text are technically still separate, saving the image does not save the text on top so what you save is just the template of a certificate and no text.
Is there a way to save both image and text as one, as if the text was pressed onto the image and was the same object? If so, I would appreciate being pointed in the right direction to know how to do this. Any ideas or code to save an image and text as one it would be very helpful.
Thanks.

May this help you
private void makeCertificate(string name, string id, string otherDetails) //You can pass any other details as well
{
System.Drawing.Image PrePrintedCertificate;
name = name.ToUpper();
string PrePrintedCertificateName = "Certificate.jpg"; //Assuming Certificate JPG File is in the bin folder
using (FileStream stream = new FileStream(PrePrintedCertificateName, FileMode.Open, FileAccess.Read))
{
PrePrintedCertificate = System.Drawing.Image.FromStream(stream);
}
RectangleF rectf4Name = new RectangleF(655, 460, 535, 90); //rectf for Name
RectangleF rectf4ID = new RectangleF(655, 560, 400, 40);
System.Drawing.Rectangle rect;
Bitmap picEdit = new Bitmap(PrePrintedCertificate, new System.Drawing.Size(1241, 1756));
using (Graphics g = Graphics.FromImage(picEdit))
{
//g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Red, 2), 662, 530, 90, 40);
//I have used upper line to see where is my RectangleF creating on the image
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
StringFormat sf1 = new StringFormat();
sf1.Alignment = StringAlignment.Near;
//g.DrawImage(codeImage, rect); //If you wanted to draw another image on the certificate image
g.DrawString(name, new System.Drawing.Font("Thaoma", 26, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, rectf4Name, sf);
g.DrawString(Track.Text, new System.Drawing.Font("Thaoma", 14, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, rectf4ID, sf1);
}
try
{
if (File.Exists(id + ".jpg"))
File.Delete(id + ".jpg");
picEdit.Save(id + ".jpg", ImageFormat.Jpeg);
picEdit.Dispose();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
Things to note here is that this image is a A4 size paper image with portrait orientation. You probably need to change Bitmap picEdit = new Bitmap(PrePrintedCertificate, new System.Drawing.Size(1241, 1756)); to Bitmap picEdit = new Bitmap(PrePrintedCertificate, new System.Drawing.Size(1756,1241));
Another thing is the names and other details has been printed on the image with random place but you can see where exactly you wish to print the details.
You can look where it will get printed using g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Red, 2), 662, 530, 90, 40); the Parameters you gonna pass here will be same as the RectangleF Parameters.

Save the graphic as an SVG and add the text using a text object.
You can also use CSS within the SVG to style the text.
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<text x="20" y="40">Example SVG text 1</text>
</svg>

Related

Failure in writing a BMP file

I am trying to generate a BMP file that has some text. I created a winform application and I can succesfully create the BMP (I displayed it on a picture Box with no problems). However when I save it to a file, I just got a black image.
My code is
private void btnNameUsage_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(width, height);
string name = "Hello how are you";
string date = DateTime.Now.Date.ToString();
Graphics thegraphics = Graphics.FromImage(bmp);
string complete = date+"\n"+name ;
using (Font font1 = new Font("Arial", 24, FontStyle.Regular, GraphicsUnit.Pixel))
using (var sf = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center,
})
{
thegraphics.DrawString(complete, font1, Brushes.Black, new Rectangle(0, 0, bmp.Width, bmp.Height), sf);
}
picBoxImage.Image = bmp; //THIS WORKS
//thegraphics.Flush();//I am not sure this is necessary and it changes nothing anyway
bmp.Save(#"theImage.bmp",ImageFormat.Bmp);//I tried only one argument but it gave a png file. Now only a black BMP
}
What am I doing wrong here?
The reason why PNG works and BMP doesn't is that PNG allows transparency in the image. In BMP the transparent parts of your image are rendered black (since it has to drop the alpha channel). Your text is also using a black brush, so you will get a black image.
For on-screen rendering this is not an issue, since there, transparency is supported.

Blurry and large image barcode being generated using a plugin in Windows Form

Going through the steps mentioned here
and using IDAutomationCode39, I am getting the barcode image, however they are very blurr and only scans bigger size images. My barcode id will be upto 30 characters long, which is causing a very wide barcode image. Where could the problem lie? Is it the IDAutomationCode39 or my setting in my button click event below?
private void button1_Click(object sender, EventArgs e)
{
string abbre = GenerateProdCodeFromProductName();
txt2.Text = abbre;
string barcode = txt1.Text;
Bitmap bitm = new Bitmap(barcode.Length * 45, 160);
bitm.SetResolution(240, 240);
using (Graphics graphic = Graphics.FromImage(bitm))
{
Font newfont = new Font("IDAutomationHC39M", 6);
PointF point = new PointF(5f, 5f);
SolidBrush black = new SolidBrush(Color.Black);
SolidBrush white = new SolidBrush(Color.White);
graphic.FillRectangle(white, 0, 0, bitm.Width, bitm.Height);
graphic.DrawString("*" + barcode + "*", newfont, black, point);
}
using (MemoryStream Mmst = new MemoryStream())
{
bitm.Save("ms", ImageFormat.Jpeg);
pictureBox1.Image = bitm;
pictureBox1.Width = bitm.Width;
pictureBox1.Height = bitm.Height;
}
}
Thank you.
I don't see any PlugIn reference in your code, you are just using a Code39 ASCII font to print a Barcode on a Bitmap.
The problem I see is that the size of the resulting Bitmap is unscaled.
What I mean is, you let the size of the Barcode determine the size of the final graphic image.
It is usually the opposite. You have some defined dimensions for a Bitmap, because of layout constraints: you have to print the barcode to a label, for example.
If the generated Barcode is wider than its container, you have to normalize it (scale it to fit).
Here is what I propose. The size of the Bitmap if fixed (300, 150). When the Barcode is generated, its size is scaled to fit the Bitmap size.
The quality of the image is preserved, using an Bicubic Interpolation in case of down scaling. The resulting graphics is also Anti-Aliased.
(Anti-Alias has a good visual render. May not be the best choice for printing. It also depends on the printer.)
The generated Bitmap is then passed to a PictureBox for visualization and saved to disk as a PNG image (this format because of its loss-less compression).
Here is the result:
string Barcode = "*8457QK3P9*";
using (Bitmap bitmap = new Bitmap(300, 150))
{
bitmap.SetResolution(240, 240);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
Font font = new Font("IDAutomationSHC39M", 10, FontStyle.Regular, GraphicsUnit.Point);
graphics.Clear(Color.White);
StringFormat stringformat = new StringFormat(StringFormatFlags.NoWrap);
graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
graphics.TextContrast = 10;
PointF TextPosition = new PointF(10F, 10F);
SizeF TextSize = graphics.MeasureString(Barcode, font, TextPosition, stringformat);
if (TextSize.Width > bitmap.Width)
{
float ScaleFactor = (bitmap.Width - (TextPosition.X / 2)) / TextSize.Width;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.ScaleTransform(ScaleFactor, ScaleFactor);
}
graphics.DrawString(Barcode, font, new SolidBrush(Color.Black), TextPosition, StringFormat.GenericTypographic);
bitmap.Save(#"[SomePath]\[SomeName].png", ImageFormat.Png);
this.pictureBox1.Image = (Bitmap)bitmap.Clone();
font.Dispose();
}
}

Adding dynamic text to image

I currently have an image which gets displayed to the user, I'm trying to add dynamic text to this image based on two parameters passed in.
The issue I have is when I step through the code it all seems to be working correctly, however when I see the image on the screen after the below code has run it doesn't have the text on it.
Below is my current set up of code:
public ActionResult GenerateImage(string savingAmount, string savingDest)
{
// Hardcoding values for testing purposes.
savingAmount = "25,000.00";
savingDest = "Canada";
PointF firstLocation = new PointF(10f, 10f);
PointF secondLocation = new PointF(10f, 50f);
Image imgBackground = Image.FromFile(Server.MapPath("~/assets/img/fb-share.jpg"));
int phWidth = imgBackground.Width; int phHeight = imgBackground.Height;
Bitmap bmBackground = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
bmBackground.SetResolution(72, 72);
Graphics grBackground = Graphics.FromImage(bmBackground);
Bitmap bmWatermark;
Graphics grWatermark;
bmWatermark = new Bitmap(bmBackground);
bmWatermark.SetResolution(imgBackground.HorizontalResolution, imgBackground.VerticalResolution);
grWatermark = Graphics.FromImage(bmWatermark);
grBackground.SmoothingMode = SmoothingMode.AntiAlias;
// Now add the dynamic text to image
using (Graphics graphics = Graphics.FromImage(imgBackground))
{
using (Font arialFont = new Font("Arial", 10))
{
grWatermark.DrawString(savingAmount, arialFont, Brushes.White, firstLocation);
grWatermark.DrawString(savingDest, arialFont, Brushes.White, secondLocation);
}
}
imgBackground.Save(Response.OutputStream, ImageFormat.Png);
Response.ContentType = "image/png";
Response.Flush();
Response.End();
return null;
}
As mentioned after this code has run, I then see the image in the browser however text is not displayed on the image, can anyone see / suggest what maybe causing this issue?
I feel like there are way to many images in that code for what you are describing as the intent of the code. What you want should reduce to this:
Load Image
Create Graphics on that Image
Draw into the Graphics and close
Output image to client
In the code sample you provided you are opening the Graphics on imgBackground then drawing into the grWatermark graphics which is opened earlier on against an image you never touch again.
public ActionResult GenerateImage(string savingAmount, string savingDest)
{
// Hardcoding values for testing purposes.
savingAmount = "25,000.00";
savingDest = "Canada";
PointF firstLocation = new PointF(10f, 10f);
PointF secondLocation = new PointF(10f, 50f);
Image imgBackground = Image.FromFile(Server.MapPath("~/assets/img/fb-share.jpg"));
using (Graphics graphics = Graphics.FromImage(imgBackground))
{
using (Font arialFont = new Font("Arial", 10))
{
graphics.DrawString(savingAmount, arialFont, Brushes.White, firstLocation);
graphics.DrawString(savingDest, arialFont, Brushes.White, secondLocation);
}
}
imgBackground.Save(Response.OutputStream, ImageFormat.Png);
Response.ContentType = "image/png";
Response.Flush();
Response.End();
return null;
}

Screen shot of C# code file

I want to take a screen shot of full code from visual studio single file.
is it possible?
if yes, how?
print to something like a PDF writer? or 'Microsoft Office Document Image Writer'?
Think that would be the way to go.
You can try this
File
Print
Select Printer Name as Microsoft XPS Document Writer
Press OK
To support colors, you can paste the code into an enormous RichTextBox (or regular-sized with NumericUpDowns to control width and height) and have a button that will do:
var bitmap = new Bitmap(this.richTextBox1.Width, this.richTextBox1.Height);
this.richTextBox1.DrawToBitmap(bitmap, new Rectangle(Point.Empty, bitmap.Size));
bitmap.Save("code.bmp");
Legacy (doesn't support colors):
var allCode = "...copy all of the code into here";
var font = new Font("Arial", 13);
SizeF size;
using (var g = Graphics.FromImage(new Bitmap(1, 1)))
{
size = g.MeasureString(allCode, font);
}
var bitmap = new Bitmap((int)size.Width + 20, (int)size.Height + 20);
using (var g = Graphics.FromImage(bitmap))
{
g.DrawString(allCode, font, Brushes.Black, 10, 10);
}
bitmap.Save("code.bmp");
You can use this:
Bitmap BmpScreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
Graphics ScreenShot = Graphics.FromImage(BmpScreen);
ScreenShot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
string file = "C:\\test.jpg";
BmpScreen.Save(file, System.Drawing.Imaging.ImageFormat.Png);
is necessary: using System.Drawing;

How to create image from text strings

I perform a screen capture and get an image with a text in it. Let consider the text in the image to read - 'Hello'.
Now, I would like to 'create' an image from text 'Hello' which has all the same properties (font style, size, pixel format..) as the text - Hello from my captured image.
I'm using the following code to convert the string - Hello to an image.
string str = "Hello";
Bitmap bmp = new Bitmap(74, 16, PixelFormat.Format32bppArgb);
using (Graphics gfx = Graphics.FromImage((Image)bmp))
{
Font font = new Font("Tahoma", 11, FontStyle.Regular, GraphicsUnit.Pixel);
gfx.FillRectangle(Brushes.Transparent, new RectangleF(0, 0, bmp.Width, bmp.Height));
gfx.FillRectangle(Brushes.Black, 0, 0, 74, 16);
gfx.DrawString(str, font, new SolidBrush(Color.White), 1, 1);
bmp.Save(#"C:\temp\" + str + ".bmp", ImageFormat.Bmp);
}
The two images (one from screen capture, and second from creating) are not the same.
How do I create an image with text which would match exactly to the image with text from the screen capture ?
Here is the code I use to screen capture from the third party application....
Rectangle rect = new Rectangle(194, 41, 74, 16);
using (Bitmap bmpScreenShot = new Bitmap(rect.Width, rect.Height))
{
using (Graphics gfxScreenShot = Graphics.FromImage(bmpScreenShot))
{
gfxScreenShot.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmpScreenShot.Size, CopyPixelOperation.SourceCopy);
gfxScreenShot.Dispose();
MemoryStream imageStream = new MemoryStream();
bmpScreenShot.Save(imageStream, ImageFormat.Bmp);
bmpScreenShot.Save(#"c:\temp\pic1_0.bmp");
}
}
I assume you're trying to implement an OCR. I've never tried anything like it, and can imagine it get's quite complicated. You might want to check out other (open-source) OCRs, like:
OCR in the Cloud, by Microsoft
Tessnet2

Categories