title: Read and write a PNG file using libpng in C
body: <p>My goal is to read a PNG file, change the pixel values and store the updated PNG file using <a href="https://en.wikipedia.org/wiki/libpng" rel="nofollow noreferrer">libpng</a>.</p>
  <p>I wrote two functions called <code>read_png</code> and <code>write_png</code> by following the <a href="http://www.libpng.org/pub/png/libpng-manual.txt" rel="nofollow noreferrer">official libpng manual</a>. The example code doesn't change the pixel values, because it's a <a href="https://stackoverflow.com/help/minimal-reproducible-example">minimum, reproducible example</a>. It also doesn't check if the input file is actually a PNG file.</p>
  <pre><code>#include &lt;png.h&gt;
  
  png_infop info_ptr;
  png_bytepp row_pointers;
  
  void read_png(char *file_name)
  {
      FILE *fp = fopen(file_name, &quot;rb&quot;);
      png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
      png_infop info_ptr = png_create_info_struct(png_ptr);
      png_init_io(png_ptr, fp);
      png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
      row_pointers = png_get_rows(png_ptr, info_ptr);
      png_destroy_read_struct(&amp;png_ptr, &amp;info_ptr, NULL);
      fclose(fp);
  }
  
  void write_png(char *file_name)
  {
      FILE *fp = fopen(file_name, &quot;wb&quot;);
      png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
      png_init_io(png_ptr, fp);
      png_set_rows(png_ptr, info_ptr, row_pointers);
      png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
      png_destroy_write_struct(&amp;png_ptr, &amp;info_ptr);
      fclose(fp);
  }
  
  int main(int argc, char *argv[])
  {
      read_png(argv[1]);
      write_png(argv[2]);
      return 0;
  }
  </code></pre>
  <p>The code compiles without any errors.</p>
  <pre><code>$ gcc -o rw_png -lpng rw_png.c
  </code></pre>
  <p>And the program can be run with two arguments.</p>
  <pre><code>$ ./rw_png input.png output.png
  </code></pre>
  <p>The problem is, that although <code>output.png</code> is created, it's an empty file instead of a PNG file.</p>
  <pre><code>$ file output.png
  output.png: empty
  </code></pre>