Skip to content

Commit 225d2b5

Browse files
committed
feat(examples): add scripts for deleting and filling selections and exporting documents with options
Signed-off-by: longhao <hal.long@outlook.com>
1 parent fc4a2ec commit 225d2b5

File tree

3 files changed

+147
-2
lines changed

3 files changed

+147
-2
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""This script demonstrates how to delete and fill a selection in one operation."""
2+
3+
# Import built-in modules
4+
import os
5+
6+
# Import third-party modules
7+
from photoshop import Session
8+
from photoshop.api import SolidColor
9+
import photoshop.api as ps
10+
11+
# Import local modules
12+
from _psd_files import get_psd_files
13+
14+
def delete_and_fill_selection(doc, fill_type, mode=None, opacity=None, preserve_transparency=None):
15+
"""Delete current selection and fill it with specified color.
16+
17+
Args:
18+
doc: The active document.
19+
fill_type (SolidColor): The color to fill the selection with.
20+
mode (ColorBlendMode, optional): The color blend mode.
21+
opacity (int, optional): The opacity value.
22+
preserve_transparency (bool, optional): If true, preserves transparency.
23+
"""
24+
# First fill the selection
25+
doc.selection.fill(fill_type, mode, opacity, preserve_transparency)
26+
# Then deselect
27+
doc.selection.deselect()
28+
29+
def main():
30+
"""Create a selection and fill it with a solid color."""
31+
psd_file = get_psd_files()["export_layers_as_png.psd"]
32+
33+
# Initialize Photoshop application
34+
app = ps.Application()
35+
36+
# Open the test file
37+
if not os.path.exists(psd_file):
38+
raise FileNotFoundError(f"Test file not found: {psd_file}")
39+
app.load(psd_file)
40+
41+
# Get the active document
42+
doc = app.activeDocument
43+
44+
# Create a rectangular selection
45+
doc.selection.select(((100, 100), (400, 100), (400, 300), (100, 300)))
46+
47+
# Create a solid color (red in this case)
48+
red_color = SolidColor()
49+
red_color.rgb.red = 255
50+
red_color.rgb.green = 0
51+
red_color.rgb.blue = 0
52+
53+
# Delete and fill the selection
54+
delete_and_fill_selection(doc, red_color, opacity=80)
55+
56+
# Save the changes
57+
doc.save()
58+
59+
print("Selection has been filled with red color.")
60+
61+
if __name__ == "__main__":
62+
main()
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""This example demonstrates how to export a document with different formats.
2+
3+
References:
4+
https://github.com/loonghao/photoshop-python-api/issues/368
5+
"""
6+
7+
# Import built-in modules
8+
import os
9+
10+
# Import third-party modules
11+
from photoshop import Session
12+
from photoshop.api.enumerations import DitherType
13+
from photoshop.api.enumerations import ExportType
14+
from photoshop.api.enumerations import SaveDocumentType
15+
from photoshop.api.save_options.png import PNGSaveOptions
16+
from photoshop.api.save_options.jpg import JPEGSaveOptions
17+
from photoshop.api.save_options.png import ExportOptionsSaveForWeb
18+
19+
20+
def main():
21+
"""Export document with different formats."""
22+
psd_file = os.path.join(os.path.dirname(__file__), "files", "export_layers_as_png.psd")
23+
if not os.path.exists(psd_file):
24+
raise FileNotFoundError(
25+
f"File not found: {psd_file}"
26+
)
27+
28+
# Start a new photoshop session
29+
with Session(psd_file, "open") as ps:
30+
doc = ps.active_document
31+
32+
# Export as PNG-24
33+
png_path = os.path.join(os.path.dirname(__file__), "exported_png24.png")
34+
png_options = PNGSaveOptions()
35+
png_options.interlaced = False # Disable interlacing for better quality
36+
png_options.compression = 0 # Set compression to 0 for maximum quality
37+
doc.saveAs(png_path, png_options, True) # True for saving as copy
38+
print(f"Exported PNG-24: {png_path}")
39+
40+
# Export as JPEG with high quality
41+
jpg_path = os.path.join(os.path.dirname(__file__), "exported_jpeg.jpg")
42+
jpg_options = JPEGSaveOptions()
43+
jpg_options.quality = 12 # Set quality to maximum (12)
44+
jpg_options.embedColorProfile = True # Preserve color profile
45+
jpg_options.formatOptions = 1 # Use standard baseline format
46+
jpg_options.scans = 3 # Enable progressive scanning
47+
jpg_options.matte = 1 # No background color (matte)
48+
doc.saveAs(jpg_path, jpg_options, True) # True for saving as copy
49+
print(f"Exported JPEG: {jpg_path}")
50+
51+
# Export as GIF using Save for Web
52+
gif_path = os.path.join(os.path.dirname(__file__), "exported_gif.gif")
53+
gif_options = ExportOptionsSaveForWeb()
54+
gif_options.format = SaveDocumentType.CompuServeGIFSave # Set format to GIF
55+
gif_options.colors = 256 # Use maximum number of colors (256)
56+
gif_options.dither = DitherType.NoDither # Disable dithering for sharper edges
57+
gif_options.transparency = True # Preserve transparency in the GIF
58+
doc.exportDocument(gif_path, ExportType.SaveForWeb, gif_options)
59+
print(f"Exported GIF: {gif_path}")
60+
61+
62+
if __name__ == "__main__":
63+
main()

photoshop/api/save_options/png.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from photoshop.api._core import Photoshop
33
from photoshop.api.enumerations import ColorReductionType
44
from photoshop.api.enumerations import DitherType
5+
from photoshop.api.enumerations import SaveDocumentType
56

67

78
class ExportOptionsSaveForWeb(Photoshop):
@@ -11,12 +12,22 @@ class ExportOptionsSaveForWeb(Photoshop):
1112

1213
def __init__(self):
1314
super().__init__()
14-
self.format = 13 # PNG
15+
self._format = SaveDocumentType.PNGSave # Default to PNG
1516
self.PNG8 = False # Sets it to PNG-24 bit
1617

18+
@property
19+
def format(self) -> SaveDocumentType:
20+
"""The file format to use. One of the SaveDocumentType constants."""
21+
return self._format
22+
23+
@format.setter
24+
def format(self, value: SaveDocumentType):
25+
"""Set the file format to use."""
26+
self._format = value
27+
1728
@property
1829
def PNG8(self) -> bool:
19-
"""If true, uses 8 bits. If false, uses 24 bits. Valid only when format = PNG."""
30+
"""If true, uses 8 bits. If false, uses 24 bits. Valid only when 'format' = PNG."""
2031
return self.app.PNG8
2132

2233
@PNG8.setter
@@ -59,6 +70,15 @@ def dither(self) -> DitherType:
5970
def dither(self, value: DitherType):
6071
self.app.dither = value
6172

73+
@property
74+
def optimized(self) -> bool:
75+
"""If true, optimization is enabled."""
76+
return self.app.optimized
77+
78+
@optimized.setter
79+
def optimized(self, value: bool):
80+
self.app.optimized = value
81+
6282
@property
6383
def quality(self) -> int:
6484
"""The quality of the output image, from 0 to 100."""

0 commit comments

Comments
 (0)