我使用Python和GDK加载图片:
Pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
然后我想编辑这个pixbuf的像素并将其显示在GTKImage上。
这是我尝试的内容:
pixList = Pixbuf.get_pixels()
然后:
Pixbuf = GdkPixbuf.Pixbuf.new_from_data(pixList, Pixbuf.get_colorspace(), Pixbuf.get_has_alpha(), Pixbuf.get_bits_per_sample(), Pixbuf.get_width(), Pixbuf.get_height(), Pixbuf.get_rowstride())
但是当我在GTKImage中显示这个Pixbuf时,它只显示黑色像素。 它适用于第一个new_from_file()。
它有什么问题?
答案 0 :(得分:0)
Gtk 不提供和支持在 pixbuf 中设置像素,但您可以解决这个问题并创建/加载和写入新文件,如下所示:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Pango
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
from gi.repository import GObject as gobject
from gi.repository import GtkSource as gtksource
from gi.repository.GdkPixbuf import Pixbuf
from gi.repository import GtkSource
from gi.repository import GObject
from gi.repository import Gtk as gtk, GdkPixbuf
width = 800
height = 500
def draw_pixel(pixels, x, y, rgb):
# make sure pixel data is reasonable
x = min(x, width)
y = min(y, height)
r = min(rgb[0], 255)
g = min(rgb[1], 255)
b = min(rgb[2], 255)
# insert pixel data at right location in bytes array
i = y*width + x
pixels[i*3 + 0] = r
pixels[i*3 + 1] = g
pixels[i*3 + 2] = b
def init_pixels(width, height, color=[0,0,0]):
pixels = bytearray(width*height*3)
for i in range(width):
for j in range(height):
draw_pixel(pixels, i,j, color)
return pixels
def save_file(file_name, pixels):
with open(file_name, 'wb') as f:
f.write(header)
# one-liner to write data
f.write(bytes(pixels))
def get_pixels(image):
raw_pixels = image.get_pixbuf().get_pixels()
return bytearray(raw_pixels)
# header for PNM file
s = 'P6\n\n' + str(width) + " " + str(height) + ' \n255\n'
header = bytes(s, 'ascii')
# OPTIONAL
# create an input file
# l = GdkPixbuf.PixbufLoader.new_with_type('pnm')
# l.write(header)
# # create a blank red file
# l.write(bytes(init_pixels(width, height, [255,0,0])))
# input_image = gtk.Image.new_from_pixbuf(l.get_pixbuf())
# # save to disk
# save_file("input.pnm", get_pixels(input_image))
# retrieve image from disk
image = gtk.Image.new_from_file("input.pnm")
pixels = get_pixels(image)
# add a blue square
for i in range(50,100):
for j in range(50,100):
draw_pixel(pixels, i,j, [0,0,255])
# process and save to new output file
save_file("output.pnm", pixels)
# retrieve from disk
output_image = gtk.Image.new_from_file("output.pnm")
w = gtk.Window()
w.add(output_image)
w.show_all()
gtk.main()
以下示例显示了添加到输入图像中的蓝色方块: