2

How do I convert text into an image? The image resolution has to be really small ~30x30 to 100x100 and should only be a single color.

I've tried using GDI to do it but it generates text with multiple colors because of aliasing and whatnot.

3
  • Not sure what your exact problem is with your code, but rendering on monochrome bitmap should work fine... Commented Aug 28, 2015 at 1:01
  • What exactly do you mean by 'convert text into pixels'? Could you be more specific? Maybe an example? Commented Aug 28, 2015 at 1:11
  • I basically want to be able to convert a string into a very tiny image, which if blown up 100x looks like text. Imagine something like 8bit art/text. There are very few pixels involved, but each pixel is huge. Commented Aug 28, 2015 at 5:18

2 Answers 2

3

For an image, render the textblock to a bitmap using the RenderTargetBitmap.Render() as described here. Here is an example where you render a TextBlock "textblock", and assign the result to an Image "image"

var bitmap = new RenderTargetBitmap();
bitmap.Render(textblock);
image.Source = bitmap;
Sign up to request clarification or add additional context in comments.

Comments

0

Try this. You can use the GraphicsObject in the code below to set the default type for text rendering which is no antialiasing. You can set the color using any combination of RGB that you want (single or multiple). I have used color brown here

private Bitmap CreateImageFromText(string Text)
{
       // Create the Font object for the image text drawing.
        Font textFont = new Font("Arial", 25, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);

        Bitmap ImageObject = new Bitmap(30, 30);
        // Add the anti aliasing or color settings.
        Graphics GraphicsObject = Graphics.FromImage(ImageObject);

        // Set Background color
        GraphicsObject.Clear(Color.White);
        // to specify no aliasing
        GraphicsObject.SmoothingMode = SmoothingMode.Default;
        GraphicsObject.TextRenderingHint = TextRenderingHint.SystemDefault;
        GraphicsObject.DrawString(Text, textFont, new SolidBrush(Color.Brown), 0, 0);
        GraphicsObject.Flush();

       return (ImageObject);
  }

You can call this function with the string you like and than use Bitmap.Save method to save your image. Please note you will need to use namespaces System.Drawing, System.Drawing.Drawing2D, System.Drawing.Text

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.