Search code examples
c#.netimage-processingvisual-studio-2012raster

Unable to create a scalable png image using C# in .NET


I am trying to create an image based on a string. The image needs to be raster (otherwise it will lose resolution if I need to zoom out). I am using the following code:

Bitmap bitmapimage = new Bitmap(200, 100);
Graphics bitmapGraphics = Graphics.FromImage(bitmapimage );   
bitmapGraphics .DrawString("test", new Font("Arial",50), Brushes.Black, new Point(0, 0));              
bitmapimage .Save("Image.png", System.Drawing.Imaging.ImageFormat.png);
textPictureBox.Image = bitmapimage ;

What I get is an image like this (after zooming):

test image

Why is this?


Solution

  • I think you misunderstand what "raster" means. Raster images are grids, with one pixel at each grid location. When you zoom on a raster image far enough the grid becomes clearly visible, even with techniques like anti-aliasing.

    Vector graphics, on the other hand, are algorithm based. They store instructions on how to reproduce an image on a given canvas. When you zoom a vector image, the image will stay sharp because it's still following the instruction, rather than simply scaling the previous rendering.

    All of the major image types (bmp, gif, png, jpeg) are raster types, and do not support vector graphics. The png image is your example is rastered... in fact, it's impossible to create a png image this is not rastered. An example of a vector image is certain font types or Photoshop (psd) files (sort of... in practice, Photoshop files tend to be more raster than vector in the end).

    In this case, probably the easiest solution is to draw the image very large in the first place... large enough that you won't need to zoom in, and use a large enough font to fill the space. You also need to make sure that you are using a font that is fully vector-drawn.