Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a PNG file with C#?

Tags:

c#

png

I'm trying to generate a PNG file using C#. Everything I google seems to be WPF related. My issue is, I need to create a PNG 50x50 square filled with green in .NET 2.0.

My question is, how do I do this? I was looking in the System.Drawing namespace. But after all of that, I feel I'm way off. Can someone give me some pointers?

like image 296
Villager Avatar asked Jan 03 '11 13:01

Villager


People also ask

How do I create a .png file?

Open the image you want to convert into PNG by clicking File > Open. Navigate to your image and then click “Open.” Once the file is open, click File > Save As. In the next window make sure you have PNG selected from the drop-down list of formats, and then click “Save.”

What algorithm does PNG use?

PNG uses DEFLATE, a non-patented lossless data compression algorithm involving a combination of LZ77 and Huffman coding. Permissively-licensed DEFLATE implementations, such as zlib, are widely available.

What is meant by PNG file?

What is a PNG file? PNG is short for Portable Network Graphic, a type of raster image file. It's particularly popular file type with web designers because it can handle graphics with transparent or semi-transparent backgrounds.


3 Answers

You can create a bitmap with the size you want, then create a Graphics object to be able to draw on the bitmap. The Clear method is the simplest way to fill the image with a color. Then save the image using the PNG format:

using (Bitmap b = new Bitmap(50, 50)) {   using (Graphics g = Graphics.FromImage(b)) {     g.Clear(Color.Green);   }   b.Save(@"C:\green.png", ImageFormat.Png); } 
like image 147
Guffa Avatar answered Oct 03 '22 12:10

Guffa


Here is the code for you:

Bitmap bmp = new Bitmap(50,50); Graphics g = Graphics.FromImage(bmp); g.FillRectangle(Brushes.Green, 0, 0, 50, 50); g.Dispose(); bmp.Save("filepath", System.Drawing.Imaging.ImageFormat.Png); bmp.Dispose(); 
like image 22
honibis Avatar answered Oct 03 '22 13:10

honibis


You can generate png file by the following way -

FileInfo fi = new FileInfo(@"D:\bango.png");
FileStream fstr = fi.Create();
Bitmap bmp = new Bitmap(50, 50);
bmp.Save(fstr, ImageFormat.Png);
fstr.Close();
fi.Delete();
like image 20
Kiva Yor Avatar answered Oct 03 '22 13:10

Kiva Yor