Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Python] In-memory save png
#5
Yes, you are right. It would be total waste of time. I "solved" it now. "Solved" because, it is not beautiful code, but better, than storing a file on drive (Windows does not have such a feature as "tmpfs" as far as I know), which is deleted immediately after the sending, only needs to exist to retrieve the png bytes.

The solution makes use of Gegl.Node for a preprocessing to convert the Gimp.Layer into a GdkPixbuf in order to store it as png using save_to_bufferv().

I want to share it anyway, maybe somebody find it useful or as inspiration:

Code:
def export_layer_to_png_bytes(layer:Gimp.Layer) -> bytes:
   """
   Converts a given layer into PNG bytes after applying gamma correction.

   Parameters:
   layer (Gimp.Layer): The input layer to be converted.

   Returns:
   bytes: The PNG bytes representing the converted image.
   """
   Gegl.init(None)

   width = layer.get_width()
   height = layer.get_height()
   source_buffer = layer.get_buffer()

   # Gamma correction for GdkPixbuf
   node = Gegl.Node()
   # Input node
   load = node.create_child("gegl:buffer-source")
   # Unpremultiply node
   unpremul = node.create_child("gegl:unpremultiply")
   # Gamma correction node
   gamma = node.create_child("gegl:gamma")
   # Output node
   save = node.create_child("gegl:write-buffer")

   # Connect the source buffer from input layer to input node
   load.set_property("buffer", source_buffer)

   # Connect a result buffer to output layer node
   result_buffer = Gegl.Buffer.new("RGBA u8", 0, 0, width, height)
   save.set_property("buffer", result_buffer)

   # Set gamma correction to non-linear sRGB for GdkPixbuf
   gamma.set_property("value", 1.0 / 2.2)

   # Now connect the graph nodes to each other [load] -> [unpremul] -> [gamma] -> [save]
   load.connect_to("output", unpremul, "input")
   unpremul.connect_to("output", gamma, "input")
   gamma.connect_to("output", save, "input")

   # Baam!
   save.process()

   # Help to retrieve the bytes from result buffer after gamma correction for GdkPixbuf conversion
   rect = Gegl.Rectangle.new(0, 0, width, height)
   pixel_bytes = result_buffer.get(rect, 1.0, "RGBA u8", Gegl.AbyssPolicy.CLAMP)

   rowstride = width * 4
   gbytes = GLib.Bytes.new(pixel_bytes)
   pixbuf = GdkPixbuf.Pixbuf.new_from_bytes(gbytes, GdkPixbuf.Colorspace.RGB, True, 8, width, height, rowstride)

   success, png_bytes = pixbuf.save_to_bufferv("png", [], [])
   if not success:
       Gimp.message("Pixbuf export to png bytes failed")
       png_bytes = bytes()

   return png_bytes
Reply


Messages In This Thread
[Python] In-memory save png - by DunkleMaterie - Yesterday, 08:34 PM
RE: [Python] In-memory save png - by DunkleMaterie - 6 hours ago

Forum Jump: