我目前正在制作一个 MVC 元素,用户将收到一个显示在页面上的证书。证书是一个图像,然后使用文本重叠图像,其中将打印用户名和其他信息,使用 css 将文本格式化为图像的正确部分。
由于图像和文本在技术上仍然是分开的,保存图像不会将文本保存在顶部,因此您保存的只是证书模板,没有文本。
有没有一种方法可以将图像和文本保存为一个,就好像文本被压到图像上并且是同一个对象一样?如果是这样,我将不胜感激地指出正确的方向以了解如何做到这一点。任何将图像和文本保存为一个的想法或代码都会非常有帮助。
谢谢。
最佳答案
希望这对你有帮助
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);
}
}
这里需要注意的是,这张图片是 A4
尺寸纸张图像纵向。您可能需要更改 Bitmap picEdit = new Bitmap(PrePrintedCertificate, new System.Drawing.Size(1241, 1756));
至Bitmap picEdit = new Bitmap(PrePrintedCertificate, new System.Drawing.Size(1756,1241));
另一件事是名称和其他详细信息已打印在图像上的随机位置,但您可以看到要打印详细信息的确切位置。
您可以使用 g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Red, 2), 662, 530, 90, 40);
查看打印位置您要在此处传递的参数将与 RectangleF 参数相同。
关于c# - 将图像和文本保存为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40039041/