Search code examples
pythonpython-2.7numpybitmappypng

Cannot open image. Not a valid bitmap file or its format is not currently supported


I wrote this Python Program to create and save a matrix (2D Array) to a .png file. The program compiles and runs without any error. Even the IMAGE.png file is created but the png file won't open. When I try to open it in MSpaint, it says:

Cannot open image. Not a valid bitmap file or its format is not currently supported.

Source Code:

import numpy;
import png;

imagearray = numpy.zeros(shape=(512,512));

/* Code to insert one '1' in certain locations 
   of the numpy 2D Array. Rest of the location by default stores zero '0'.*/


f = open("IMAGE.png", 'wb');
f.write(imagearray);
f.close();

I don't understand where I went wrong as there is no error message. Please Help.

PS- I just want to save the matrix as an image file, so if you have a better and easy way of doing it in Python2.7, do suggest.

Thank You.


Solution

  • Here's an example that uses numpngw to create an image with a bit-depth of 1 (i.e. the values in the image are just 0s and 1s). The example is taken directly from the README file of the numpngw package:

    import numpy as np
    from numpngw import write_png
    
    # Example 2
    #
    # Create a 1-bit grayscale image.
    
    mask = np.zeros((48, 48), dtype=np.uint8)
    mask[:2, :] = 1
    mask[:, -2:] = 1
    mask[4:6, :-4] = 1
    mask[4:, -6:-4] = 1
    mask[-16:, :16] = 1
    mask[-32:-16, 16:32] = 1
    
    write_png('example2.png', mask, bitdepth=1)
    

    Here's the image:

    png image