简体   繁体   中英

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.

Not every array is compatible with image format. Assuming you're referring to a byte array, that's how you do it :

import os
import io
import Image
from array import array

def readimage(path):
    count = os.stat(path).st_size
    with open(path, "rb") as f:
        return bytearray(f.read())

bytes = readimage(path+extension)
image = Image.open(io.BytesIO(bytes))
image.save(savepath)

The code snippet was taken from here .

Hopefully this will help you, Yahli.

Here's an example that uses numpngw to create an image with a bit-depth of 1 (ie 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图像

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM