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.

M4N
  • 94,805
  • 45
  • 217
  • 260
John
  • 31
  • 1
  • 2
  • Not sure what your exact problem is with your code, but rendering on monochrome bitmap should work fine... – Alexei Levenkov Aug 28 '15 at 01:01
  • What exactly do you mean by 'convert text into pixels'? Could you be more specific? Maybe an example? – Owen James Aug 28 '15 at 01: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. – John Aug 28 '15 at 05:18

2 Answers2

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;
Community
  • 1
  • 1
Matthew Thurston
  • 720
  • 5
  • 22
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

Megha
  • 220
  • 2
  • 13