我有一个使用 Cairo image surface 的小型 PyGI 项目,然后我用 surface pattern 缩放它并在 Gtk.DrawingArea 上渲染。
我想将缩放 版本写入 PNG 文件。我尝试使用 Surface.write_to_png() 从原始表面写入,但它仅以原始(即非缩放)大小写入,所以我被困在那里。
然后我想我也许可以从 Gtk.DrawingArea 中获取渲染图像并将其写入磁盘,但我还没有找到如何在 PyGI 中执行此操作(这似乎只能在 GTK+ 2 - save gtk.DrawingArea to file 中实现) .所以我想弄清楚如何将缩放后的图像写入磁盘。
下面是创建表面、放大并渲染它的代码:
def on_drawingarea1_draw (self, widget, ctx, data=None):
# 'widget' is a Gtk.DrawingArea
# 'ctx' is the Cairo context
text = self.ui.entry1.get_text()
if text == '':
return
# Get the data and encode it into the image
version, size, im = qrencode.encode(text)
im = im.convert('RGBA') # Cairo expects RGB
# Create a pixel array from the PIL image
bytearr = array.array('B', im.tostring())
height, width = im.size
# Convert the PIL image to a Cairo surface
self.surface = cairo.ImageSurface.create_for_data(bytearr,
cairo.FORMAT_ARGB32,
width, height,
width * 4)
# Scale the image
imgpat = cairo.SurfacePattern(self.surface)
scaler = cairo.Matrix()
scaler.scale(1.0/self.scale_factor, 1.0/self.scale_factor)
imgpat.set_matrix(scaler)
ctx.set_source(imgpat)
# Render the image
ctx.paint()
下面是将表面写入 PNG 文件的代码:
def on_toolbuttonSave_clicked(self, widget, data=None):
if not self.surface:
return
# The following two lines did not seem to work
# ctx = cairo.Context(self.surface)
# ctx.scale(self.scale_factor, self.scale_factor)
self.surface.write_to_png('/tmp/test.png')
因此写入表面会创建一个非缩放图像,并且 cairo.SurfacePattern 中也没有写入方法。
我最后的办法是获取在 gtk.DrawingArea 中呈现的缩放图像,将其放入 GtkPixbuf.Pixbuf 或新表面,然后将其写入磁盘。 pixbuf 方法似乎在 GTK+ 2 中有效,但在 GTK+ 3 中无效。
那么有人知道如何将缩放后的图像写入磁盘吗?
最佳答案
好的,我找到了一个方法:
记住 Gtk.DrawingArea 派生自 Gtk.Window,我可以使用 Gdk.pixbuf_get_from_window()
函数获取将绘图区域转换为 GdkPixbuf.Pixbuf,然后使用 GdkPixbuf.Pixbuf.savev()
函数将 pixbuf 作为图像写入磁盘。
def drawing_area_write(self):
# drawingarea1 is a Gtk.DrawingArea
window = self.ui.drawingarea1.get_window()
# Some code to get the coordinates for the image, which is centered in the
# in the drawing area. You can ignore it for the purpose of this example
src_x, src_y = self.get_centered_coordinates(self.ui.drawingarea1,
self.surface)
image_height = self.surface.get_height() * self.scale_factor
image_width = self.surface.get_width() * self.scale_factor
# Fetch what we rendered on the drawing area into a pixbuf
pixbuf = Gdk.pixbuf_get_from_window(window, src_x, src_y,
image_width, image_height)
# Write the pixbuf as a PNG image to disk
pixbuf.savev('/tmp/testimage.png', 'png', [], [])
虽然这行得通,但还是很高兴看到有人可以确认这是正确的方法,或者看看是否有任何其他选择。
关于python - 将 Gtk.DrawingArea 或 Cairo 图案的内容保存到磁盘上的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8892411/