Hi,
I'm not sure that I understand the problem, but I wrote some code for exporting a selection for a mask. The original image is modified but is then restored back to its original state. I haven't tested the code, so there could be bug(s).
I've left the export PNG code out as you've stated you already have that figured-out.
Charles
I'm not sure that I understand the problem, but I wrote some code for exporting a selection for a mask. The original image is modified but is then restored back to its original state. I haven't tested the code, so there could be bug(s).
Code:
#!/usr/bin/env python3
import gi
gi.require_version('Gimp', '3.0')
from gi.repository import Gegl, Gimp # noqa
def export_selection_as_white_layer(image):
"""
Given an image, export the current selection as a new image
from the current selection filled with white and having a black background.
Steps:
1. Create a new image to hold a mask-like layer.
2. Create a white selection layer.
3. Transfer the white selection layer to the new image.
4. Export the new image as a PNG file with its alpha layer turned off.
5. Restore the original image back to its original state.
image: Gimp.Image
Has a selection that is to be exported a mask-like layer.
"""
# Create a temporary image.
w, h = image.get_width(), image.get_height()
temp_image = Gimp.Image.new(w, h, Gimp.ImageBaseType.RGB)
display = Gimp.Display.new(temp_image)
# Create a new layer for a white selection on top of the original image.
white_selection_layer = Gimp.Layer.new(
image,
"White Selection Layer",
w,
h,
Gimp.ImageType.RGBA_IMAGE,
100.,
Gimp.LayerMode.NORMAL
)
image.insert_layer(white_selection_layer, None, 0)
# Fill the selection with white.
Gimp.context_set_opacity(100.)
Gimp.context_set_paint_mode(Gimp.LayerMode.NORMAL)
Gimp.context_set_foreground(Gegl.Color.new('white'))
white_selection_layer.edit_fill(Gimp.FillType.FOREGROUND)
# Create a new layer from the white selection layer.
layer_copy = Gimp.Layer.new_from_drawable(
white_selection_layer, temp_image
)
temp_image.insert_layer(layer_copy, None, 0)
# Export the temp-image as a PNG file and without an alpha
# so that the background is black.
# * Insert export PNG code here. *
# Remove the temporary layer from the original image.
image.remove_layer(white_selection_layer)
# Delete the new image.
# display.delete()I've left the export PNG code out as you've stated you already have that figured-out.
Charles

