在 C# 中从字符串文本制作图像时如何使背景透明?

How to make backgroud transparent while make image from string text in c#?

我正在用 C# 将字符串文本转换为图像。它正确地将文本转换为图像,但我需要具有透明背景的图像。我在 google 研发方面进行了很多尝试,但 none 正在发挥作用。

我的代码如下:

string fullName = name.Trim();
Bitmap bitmap = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
string fontName = "Airin.ttf";
PrivateFontCollection privateFontCollection = new PrivateFontCollection();
privateFontCollection.AddFontFile(Server.MapPath("~/Content/fontCss/" + fontName));
FontFamily ff = privateFontCollection.Families[0];
Font font = new Font(ff, 25, FontStyle.Regular, GraphicsUnit.Pixel);
Graphics graphics = Graphics.FromImage(bitmap);
int width = (int)graphics.MeasureString(fullName, font).Width;
int height = (int)graphics.MeasureString(fullName, font).Height;
bitmap.MakeTransparent(Color.Transparent);
bitmap = new Bitmap(bitmap, new Size(width, height));
graphics = Graphics.FromImage(bitmap);
graphics.Clear(Color.White);
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
graphics.DrawString(fullName, font, Brushes.Black, 0, 0);
string fileName = Guid.NewGuid().ToString() + ".jpg";
bitmap.Save(Server.MapPath("~/UploadedDocuments/") + fileName, ImageFormat.Jpeg);
fileName = "/UploadedDocuments/" + fileName;

那么我需要在哪里更改代码以获取具有透明背景的图像?

您需要将图像保存为支持透明胶片的格式,例如 GIF 或 PNG。 JPEG 没有。

Transparent background in JPEG image

将下一行末尾的 ImageFormat 参数更改为适当的值(例如 ImageFormat.GifImageFormat.Png

bitmap.Save(Server.MapPath("~/UploadedDocuments/") + fileName, ImageFormat.Jpeg);

另外,你试过换[=​​17=]

graphics.Clear(Color.White);

改用Color.Transparent