Question

I want to render some text as image in ASP.NET. It is working well, but the text is rendered very ugly (with grey pixels around the text) even if I turn on AntiAlias (or ClearType) by changing the graphics TextRenderingHint option.

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 a link to the generated image (zoom):

enter image description here

Unzoomed image:

enter image description here

How can I solve this?

Was it helpful?

Solution

Make the imageformat PNG.

The default JPEG compression is useless.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top