【问题标题】:How to make backgroud transparent while make image from string text in c#?如何在c#中从字符串文本制作图像时使背景透明?
【发布时间】:2020-08-10 10:23:34
【问题描述】:

我在 c# 中将字符串文本转换为图像。它正在正确地将文本转换为图像,但我需要具有透明背景的图像。我在谷歌研发方面做了很多尝试,但都没有奏效。

我的代码如下:

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;

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

【问题讨论】:

  • 你得到什么结果,你想要什么?
  • 我在这里得到白色背景的图像,但是我需要透明背景的图像。

标签: c# image graphics bitmap


【解决方案1】:

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

Transparent background in JPEG image

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

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

还有,你有没有尝试过改变

graphics.Clear(Color.White);

改用Color.Transparent

【讨论】:

  • 我已经尝试使用 .Png 但它仍然显示背景白色而不是透明。
  • @HarryR 我添加了一个建议来更改您用于graphics.Clear() 呼叫的颜色。图形不是我真正喜欢的东西,但它会是我接下来要尝试的东西。
  • @HarryR 经过测试,如果您使用 graphics.Clear(Color.Transparent); 并保存到 PNG,它可以在 LinqPad 中工作。
猜你喜欢
  • 2011-03-04
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 2016-12-08
  • 2011-07-26
  • 2020-10-18
  • 2013-06-05
  • 1970-01-01
相关资源
最近更新 更多