Write on Existing Image
In this blog post you will learn all about writing text or image on existing image. I will be developing this in ASP.NET Web Forms, but you can achieve this functionality in MVC or windows forms as well. I’ve posted another blog post which generates QR Code. Actually all this was part of my recent requirement which I would like share with you.
I had a requirement to generate certificate dynamically with QR Code, candidate name, certificate number etc printed on it. Generating QR Code is already published here, candidate name and certificate number will be fetched from database which we will not discuss here.
Now in this post I will show you how to use QR Code bits or QR Code from file system and write on certificate format. For sake of this demo I’ll use seal.png file considering it a QR Code. I will randomly generate string and use it as candidate name, in real application this will be fetched from database.
How to write on Image
Let’s follow simple steps to achieve this.
Step 1: Select certificate format from file system and read it into graphics object.
Bitmap bitMapImage = new Bitmap(Server.MapPath("certificate-format.jpg"));
Graphics graphicImage = Graphics.FromImage(bitMapImage);
graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
Step 2: Generate or fetch student name (and certificate number) and write on above graphics.
string studentName = RandomString(8) + " " + RandomString(4);
graphicImage.DrawString(studentName, new Font("Arial", 20, FontStyle.Bold), SystemBrushes.WindowText, new Point(300, 250));
Step 3: Generate QR Code now or select QR Code saved somewhere in folder. I’ll be using saved version. And write QR Code on graphics which we have from step 1.
var barCodeImageSrc = new Bitmap(Server.MapPath("seal.png")); // File source maybe generated QR Code
graphicImage.DrawImage(barCodeImageSrc, new Point(570, 400));
Step 4: Now we have everything printed on certificate in graphics object, let’s use its bitmap and save into memory stream.
var memStream = new MemoryStream();
Step 5: Once saved, copy it into folder with random filename.
var fileName = new Random().Next().ToString();
using (var fileStream = new FileStream(Server.MapPath("~/Certificates/") + fileName + ".jpg", FileMode.Append, FileAccess.Write))
memStream.Position = 0;
That’s all code needed to achieve this requirement. I’ve customized this application, so that you can see some output on screen, find the output below.
In case you would like run this project yourself, I’ve posted this on GitHub here.
Hope this helps.