GdkPixbuf - Saving pixel data to file from Python

738 Views Asked by At

I am trying to save some pixels to a file using GdkPixbuf from Python in Windows. I am making use of the excellent PyGI AIO (3.14.0) binaries.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from gi.repository import Gtk, Gdk, GdkPixbuf

w, h, n = 4, 4, 4

data = bytearray(b'\x00\x00\x00\xff' * w * h)

#data = GLib.Bytes.new(b'\x00\x00\x00\xff' * w * h).get_data()

#import numpy as np
#data = np.zeros((w,h,n), np.uint8) 
#data[:,:,3] = 255
#data = data.tostring()

options = {}
pixbuf = GdkPixbuf.Pixbuf.new_from_data(data, GdkPixbuf.Colorspace.RGB, True, 8, w, h, n*w, None, None)
pixbuf.savev('screenshot.bmp', 'bmp', options.keys(), options.values())

The zoomed-in result looks as follows:

Encode to bmp (4x4).

Clearly, the first couple of pixels are corrupted. The amout of broken pixels seems to vary depending on the image dimensions. However, some of the pixel manage to stay intact. There must be an error in my code or the memory is getting corrupted somehow. It is possible to encode a larger image, and the error always appears in the first few pixels. Could this be a string encoding problem or something?

Edit: I have tested the program on OS X and the error is very similar. Therefore, it seems to be a general issue with the Python bindings to GdkPixbuf, potentially related to this. Here is a bigger PNG produced by a modified version of the script. The grid of red and green lines is the expected output, whereas the pixels in the upper half of the image are just noise.

Encode to png (10x10).

0

There are 0 best solutions below