Tutorial¶
Create an image and export it¶
Create a temporary xcf file containing a sphere and export it to png.
Source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import os
import numpy as np
from pgimp.GimpFile import GimpFile
from pgimp.util import file
from pgimp.util.TempFile import TempFile
if __name__ == '__main__':
img_path = file.relative_to(__file__, '../../../doc/source/_static/img')
png_file = os.path.join(img_path, 'sphere.png')
# generate sphere data
x = np.arange(-1, 1, 0.01)
y = np.arange(-1, 1, 0.01)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2)
# generate rgb image data
img = np.zeros(shape=(200, 200, 3), dtype=np.uint8)
img[:, :, 0] = (1-z)*255
# create temporary gimp file an export to png
with TempFile('.xcf') as tmp:
GimpFile(tmp).create('Background', img).export(png_file)
|
Result:

Create a multi layer image and export to npz¶
Create a multi layer image with a mask and export the layers to a numpy npz archive. Read the npz file, apply the mask, create a new gimp file and export it to png.
Source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | import os
import numpy as np
from pgimp.GimpFile import GimpFile
from pgimp.util import file
from pgimp.util.TempFile import TempFile
if __name__ == '__main__':
img_path = file.relative_to(__file__, '../../../doc/source/_static/img')
png_file = os.path.join(img_path, 'mask_applied.png')
height = 100
width = 200
# layer content
bg = np.zeros(shape=(height, width), dtype=np.uint8)
fg = np.ones(shape=(height, width), dtype=np.uint8) * 255
mask = np.zeros(shape=(height, width), dtype=np.uint8)
mask[:, width//4:3*width//4+1] = 255
with TempFile('.xcf') as xcf, TempFile('.npz') as npz:
# create gimp file
gimp_file = GimpFile(xcf) \
.create('Background', bg) \
.add_layer_from_numpy('Foreground', fg) \
.add_layer_from_numpy('Mask', mask)
# save layer data to numpy arrays
arr_bg = gimp_file.layer_to_numpy('Background')
arr_fg = gimp_file.layer_to_numpy('Foreground')
arr_mask = gimp_file.layer_to_numpy('Mask')
# save data as npz
np.savez_compressed(npz, bg=arr_bg, fg=arr_fg, mask=arr_mask)
# load data from npz
loaded = np.load(npz)
loaded_bg = loaded['bg']
loaded_fg = loaded['fg']
loaded_mask = loaded['mask']
# merge background and foreground using mask
mask_idxs = loaded_mask == 255
img = loaded_bg.copy()
img[mask_idxs] = loaded_fg[mask_idxs]
with TempFile('.xcf') as xcf:
# create a temporary gimp file and export to png
gimp_file = GimpFile(xcf) \
.create('Background', img) \
.export(png_file)
|
Result:
