Writing PNGs from C++

hexagonsTo continue the series on using C++ to replace MATLAB, here are some details about using the pngwriter library. Included below is a function that I use in various places to write a 2D array to a png file. This can be left in a header somewhere and used in a similar way to MATLAB’s imagesc() function.

I’d be happy to post more details if anyone is interested, and I’ll try to keep up with posts about the process I followed to port from MATLAB to C++.

Assume the array field is square with size by size elements. There is a peak-finding routine used to normalize the color map, and I call png.plot_text to write the value of max in the image:

  void array_to_png (char* filename, int size, array2 &field)
    char text[30];
    int i,j;
    double pixel;
    pngwriter png(size,size,0,filename);
    // Peak-finding for image scaling:
    double max = 1e-32; 
    for (i = 0; i < size; i++)
      for (j = 0; j  max) max = real(field(i,j)*conj(field(i,j)));

    // Image writeout.
    for (i = 0; i < size; i++)
      for (j = 0; j < size; j++)
        pixel = real(field(i,j)*conj(field(i,j)));

    sprintf(text, "%f7", max);

The only other detail is that this image will be yellow because I’ve passed equal values to the R and G parameters (B=0) in the call to png.plot().

2 thoughts on “Writing PNGs from C++

  1. Pingback: Animating PNG files « The Daily Photon

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s