Horrible image rendering using the DrawString-Method (ASP.NET)

I want to make some text as an image in ASP.NET. It works well, but the text is very ugly (with gray pixels around the text), even if I turn on AntiAlias โ€‹โ€‹(or ClearType) by changing the GraphicsRenderingHint parameter.

Here is the relevant code:

    float width;
    float height;

    System.Drawing.Text.PrivateFontCollection fontcollection = new System.Drawing.Text.PrivateFontCollection();
    // Add the custom font families
    fontcollection.AddFontFile(Server.MapPath("./Fonts/" + fontfile));


    Bitmap image = new Bitmap(10, 10);
    Graphics graphic = Graphics.FromImage(image);
    Font font = new Font(fontcollection.Families.First(), fontsize, style);

    SizeF size = graphic.MeasureString(text, font);
    width = size.Width;
    height = size.Height;

    image = new Bitmap(Convert.ToInt32(width), Convert.ToInt32(height));
    graphic = Graphics.FromImage(image);
    graphic.FillRectangle(new SolidBrush(Color.White), 0, 0, width, height);

    graphic.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
    graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bicubic;
    graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

    graphic.DrawString(text, font, Brushes.Black, new PointF(0, 0));

    Response.ContentType = "image/jpeg";
    image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

Here is a link to the generated image (scaling):

enter image description here

Unzoomed image:

enter image description here

How can i solve this?

+3
source share
1 answer

Make a PNG image.

By default, JPEG compression is useless.

+2
source

Source: https://habr.com/ru/post/1774084/


All Articles