2

I am attempting to load a PNG image into a Bitmap and save it without modifications.

I tried something along these lines:

var png = Bitmap.FromFile("t_02.png");
png.Save("t_02_out.png", ImageFormat.Png);

I also tried:

var png = Bitmap.FromFile("t_02.png");
png.Save("t_02_out.png");

In either case, the original 233kb file procuded a 356kb image. What am I doing wrong?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Deathspike
  • 8,582
  • 6
  • 44
  • 82
  • It is too much to explain with a lesser compression. PNG supports a number of image formats that GDI+ won't reproduce. You can tinker with PngBitmapEncoder if it is important, BitmapSource gives you more control over the PixelFormat. – Hans Passant Sep 15 '13 at 18:51

2 Answers2

2

PNG is compressed format. You decompress on load and compress back on save. Result does not have to be the same exactly. The difference is in the fact that originally the image was compressed more efficiently than the compressor used by your code (or, you need to fine tune compressing options). In particular, if you used to save into PNG using popular graphic editor tools, you have options to specify compression level there and hence different output for the same picture.

Putting up useful links from comments:

Community
  • 1
  • 1
Roman R.
  • 68,205
  • 6
  • 94
  • 158
  • 2
    also check these articels: [How to specify compression level?](http://bytes.com/topic/c-sharp/answers/700494-how-specify-compression-level-when-saving-loseless-pngs) and [Seeking PNG compression](http://stackoverflow.com/questions/4418454/c-seeking-png-compression-algorithm-library) – Matthias Sep 15 '13 at 15:44
0

The image in question is stored with the grey-scale color type. The specification describes:

http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html

A pixel is then be stored as a single byte. .NET saves a PNG file as 32-bit regardless of pixel format.

The closest I got is using AForge grayscale filter and storing, which turns it into a palette storage.

The result is then much closer to the original, but due to the palet it is often still larger.

Conclusion: .NET image format support is terrible. I used ImageMagic to solve .NET incompetence.

Deathspike
  • 8,582
  • 6
  • 44
  • 82