0

I am converting string text to image in c#. It's converting text to image properly but I need image with transparent background. I have try a lot with google r&d but none of that is working.

My code is as below :

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;

So where am I need to change code here for get image with transparent backgroud ?

Harry R
  • 69
  • 1
  • 11

1 Answers1

3

You need to save the image in a format that supports transparencies, such as GIF or PNG. JPEG does not.

Transparent background in JPEG image

Change the ImageFormat parameter at the end of the following line to an appropriate value (e.g. ImageFormat.Gif or ImageFormat.Png)

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

Also, have you tried changing

graphics.Clear(Color.White);

to use Color.Transparent instead?

Andy Hames
  • 619
  • 1
  • 4
  • 19
  • I have try with .Png but still it's showing background white instead of transparent. – Harry R Aug 10 '20 at 11:12
  • 1
    @HarryR I have added a suggestion to change the colour you use for the `graphics.Clear()` call. Graphics aren't really my thing, but it would be the next thing I'd try. – Andy Hames Aug 10 '20 at 11:41
  • 1
    @HarryR Tested and it's working in LinqPad if you use `graphics.Clear(Color.Transparent);` and save to PNG. – Andy Hames Aug 10 '20 at 11:55