Exemplo n.º 1
0
class TestTextItem:
    """Test the solidColor."""

    # pylint: disable=attribute-defined-outside-init
    @pytest.fixture(autouse=True)
    def setup(self, psd_file):
        """Setup for current test."""
        self.session = Session(file_path=psd_file("layer_comps"),
                               action="open",
                               auto_close=True)
        self.session.run_action()
        doc = self.session.active_document
        self.layer_compse = doc.layerComps  # -> TextItem
        yield
        self.session.close()

    def test_length(self):
        assert self.layer_compse.length == 2

    def test_getByName(self):
        layer = self.layer_compse.getByName("layer1")
        assert layer.name == "layer1"

    def test_loop_layers(self):
        for layer in self.layer_compse:
            assert layer.name

    def test_add_a_layer(self):
        self.layer_compse.add("new_layer", "test")
        assert self.layer_compse.length == 3
Exemplo n.º 2
0
 def setup(self, psd_file):
     """Setup for current test."""
     self.session = Session(file_path=psd_file("layer_comps"),
                            action="open",
                            auto_close=True)
     self.session.run_action()
     doc = self.session.active_document
     self.layer_compse = doc.layerComps  # -> TextItem
     yield
     self.session.close()
Exemplo n.º 3
0
 def setup(self, psd_file):
     """Setup for current test."""
     self.session = Session(file_path=psd_file("textitem"),
                            action="open",
                            auto_close=True)
     self.session.run_action()
     doc = self.session.active_document
     layer = doc.activeLayer
     self.text_item = layer.textItem()  # -> TextItem
     yield
class TestSolidColor:
    """Test the solidColor."""

    # pylint: disable=attribute-defined-outside-init
    @pytest.fixture(autouse=True)
    def setup(self):
        self.session = Session()
        self.solid_color = self.session.SolidColor()

    def test_cmyk_black(self):
        assert self.solid_color.cmyk.black == 0

    def test_cmyk_cyan(self):
        assert self.solid_color.cmyk.cyan == 0

    def test_cmyk_magenta(self):
        assert self.solid_color.cmyk.magenta == 0

    def test_cmyk_typename(self):
        assert self.solid_color.cmyk.typename == "CMYKColor"

    def test_yellow(self):
        assert self.solid_color.cmyk.yellow == 0

    def test_hsb_brightness(self):
        assert self.solid_color.hsb.brightness == 100

    def test_hsb_hue(self):
        assert self.solid_color.hsb.hue == 0

    def test_hsb_saturation(self):
        assert self.solid_color.hsb.saturation == 0

    def test_hsb_typename(self):
        assert self.solid_color.hsb.typename == "HSBColor"
def create_thumbnail(output_path=os.path.abspath(os.path.dirname(
    sys.argv[0]))):
    """Create a thumbnail image for currently active document.

    Args:
        output_path (str): The absolute output path of the thumbnail image.
            The default is to output to a temporary folder.
        max_resolution (int): The max resolution of the thumbnail. The default
            is `512`.

    Returns:
        str: The absolute output path of the thumbnail image.

    """

    output_path = output_path or os.path.join(mkdtemp(prefix="thumb"),
                                              "thumb.jpg")

    with Session() as ps:

        orig_name = ps.active_document.name
        thumb_name = f"{orig_name}_thumb"

        thumb_doc = ps.active_document.duplicate(thumb_name)
        thumb_doc.changeMode(2, [])
        thumb_doc.saveAs(output_path, ps.JPEGSaveOptions(), asCopy=True)
        thumb_doc.close()

        return output_path
Exemplo n.º 6
0
def create_thumbnail(output_path=None, max_resolution=512):
    """Create a thumbnail image for currently active document.

    Args:
        output_path (str): The absolute output path of the thumbnail image.
            The default is to output to a temporary folder.
        max_resolution (int): The max resolution of the thumbnail. The default
            is `512`.

    Returns:
        str: The absolute output path of the thumbnail image.

    """
    output_path = output_path or os.path.join(mkdtemp(prefix="thumb"), "thumb.jpg")

    with Session(auto_close=True) as ps:
        orig_name = ps.active_document.name
        width_str = ps.active_document.width
        height_str = ps.active_document.height
        thumb_name = f"{orig_name}_thumb"

        max_resolution = width_str / max_resolution
        thumb_width = int(width_str / max_resolution)
        thumb_height = int(height_str / max_resolution)

        thumb_doc = ps.active_document.duplicate(thumb_name)
        thumb_doc.resizeImage(thumb_width, thumb_height - 100)
        thumb_doc.saveAs(output_path, ps.JPEGSaveOptions(), asCopy=True)
        thumb_doc.close()
        return output_path
Exemplo n.º 7
0
    def setup_files_for_web_upload(self):
        psd_file = PSD_FILE["export_layers_as_png.psd"]
        with Session(psd_file, action="open") as ps:
            self.doc = ps.active_document
            self.options = ps.PDFSaveOptions()
            self.layers = self.doc.artLayers
            self.count = 1

            self.export_layers()

            ps.alert("Task done!")
            ps.echo(self.doc.activeLayer)
Exemplo n.º 8
0
def main():
    psd_file = PSD_FILE["export_layers_as_png.psd"]
    with Session(psd_file, action="open") as ps:
        doc = ps.active_document
        options = ps.PNGSaveOptions()
        layers = doc.artLayers
        for layer in layers:
            hide_all_layers(layers)
            layer.visible = True
            layer_path = os.path.join(doc.path, layer.name)
            print(layer_path)
            if not os.path.exists(layer_path):
                os.makedirs(layer_path)
            image_path = os.path.join(layer_path, f"{layer.name}.png")
            doc.saveAs(image_path, options, True)
        ps.alert("Task done!")
        ps.echo(doc.activeLayer)
Exemplo n.º 9
0
def save_tiff(output_path=os.path.abspath(os.path.dirname(sys.argv[0]))):

    output_path = output_path or os.path.join(mkdtemp(prefix="_print"),
                                              "print.tiff")

    with Session() as ps:

        orig_name = ps.active_document.name
        print_name = f"{orig_name}_print"

        print_doc = ps.active_document.duplicate(print_name)
        print_doc.Flatten()
        print_doc.saveAs(output_path, ps.TiffSaveOptions(),
                         TiffEncodingType.TIFFLZW)
        print_doc.close()

        return output_path
Exemplo n.º 10
0
def main():
    with Session() as ps:
        doc = ps.app.documents.add(29.7, 21)
        text_color = ps.SolidColor()
        text_color.rgb.red = 232
        text_color.rgb.green = 10
        text_color.rgb.blue = 224

        new_text_layer = doc.artLayers.add()
        new_text_layer.kind = ps.LayerKind.TextLayer
        new_text_layer.textItem.contents = 'Hello, World!'
        new_text_layer.textItem.position = [11.11, 9.7]
        new_text_layer.textItem.size = 40
        new_text_layer.textItem.color = text_color
        options = ps.JPEGSaveOptions(quality=5)
        path = os.path.abspath(os.path.dirname(sys.argv[0]))
        jpg = path + "\\" + sys.argv[1]
        doc.saveAs(jpg, options, asCopy=True)
        # ps.app.doJavaScript(f'alert("save to jpg: {jpg}")')
        print("Save to jpg: " + path + "\\" + sys.argv[1])
Exemplo n.º 11
0
 def extractLayerCompositionsFromPsd(self):
     fileName = self.openFileDialog()
     if fileName:
         print("Start extracting")
         with Session(fileName, action="open") as ps:
             fileName = os.path.basename(fileName)
             print("Opening PSD file", fileName)
             fileName, extension = os.path.splitext(fileName)
             if not os.path.exists(
                     os.path.join(os.getcwd(), self.activeContext)):
                 os.mkdir(self.activeContext)
             extractDir = os.path.join(
                 self.getContextDir(), fileName + "_" +
                 datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
             os.mkdir(extractDir)
             doc = ps.active_document
             options = ps.PNGSaveOptions()
             for layerComp in doc.layerComps:
                 layerComp.apply()
                 extractPath = os.path.join(extractDir,
                                            f"{layerComp.name}.png")
                 print("Extract ", extractPath)
                 doc.saveAs(extractPath, options, True)
         print("Finished extracting")
    def start():
        # Defining necessary variables
        app = GetActiveObject("Photoshop.Application")
        psApp = win32com.client.Dispatch("Photoshop.Application")
        doc = psApp.Application.ActiveDocument
        docRef = app.ActiveDocument

        # Logs the current layer
        previousLayer = docRef.activeLayer.name

        # Logs the current tool
        with Session() as ps:
            tool = ps.app.currentTool

        # Goes to the top most layer
        docRef.ActiveLayer = docRef.Layers.Item(1)

        # Plays the action "Magic Wand for Selection Script" in group "Selection Script Group" in the Actions panel
        # Sets the tool to Magic Wand
        app.DoAction('Magic Wand for Selection Script',
                     'Selection Script Group')

        # Waits for the left click
        # If it a mouse click that is not the left mouse button, does nothing
        def on_click(x, y, button, pressed):
            while button == mouse.Button.left:
                return False

        with Listener(on_click=on_click) as listener:
            listener.join()

        # After left click, sets the tool as the the tool that was selected previously
        ps.app.currentTool = tool

        # Goes to the layer that was previously active
        docRef.ActiveLayer = doc.ArtLayers[previousLayer]
"""Add slate information dynamically."""

from photoshop import Session

with Session() as adobe:
    doc = adobe.app.documents.add(2000, 2000)
    text_color = adobe.SolidColor()
    text_color.rgb.red = 255
    new_text_layer = doc.artLayers.add()
    new_text_layer.kind = adobe.LayerKind.TextLayer
    new_text_layer.textItem.contents = "Hello, World!"
    new_text_layer.textItem.position = [160, 167]
    new_text_layer.textItem.size = 40
    new_text_layer.textItem.color = text_color
    options = adobe.JPEGSaveOptions(quality=1)
    jpg = "d:/hello_world.jpg"
    doc.saveAs(jpg, options, asCopy=True)
    adobe.app.doJavaScript(f'alert("save to jpg: {jpg}")')
Exemplo n.º 14
0
"""Add metadata to current active document."""

# Import built-in modules
import os

# Import local modules
from photoshop import Session

with Session(action="new_document") as ps:
    doc = ps.active_document
    doc.info.author = os.getenv("USERNAME")
    doc.info.provinceState = "Beijing"
    doc.info.title = "My Demo"
    # Print all metadata of current active document.
    ps.echo(doc.info)
to execute the Crystallize filter.
In order to find all the IDs, see https://helpx.adobe.com/photoshop/kb/downloadable-plugins-and-content.html#ScriptingListenerplugin
This blog here explains what a script listener is http://blogs.adobe.com/crawlspace/2006/05/installing_and_1.html

References:
    https://github.com/lohriialo/photoshop-scripting-python/blob/master/ApplyCrystallizeFilterAction.py

"""

import os

from photoshop import Session

fileName = os.path.join(os.path.dirname(__file__), "layer_comps.psd")

with Session(fileName, "open") as ps:
    nLayerSets = ps.active_document.layerSets
    print(len(nLayerSets))
    nArtLayers = ps.active_document.layerSets.item(len(nLayerSets)).artLayers

    # get the last layer in LayerSets
    ps.active_document.activeLayer = ps.active_document.layerSets.item(
        len(nLayerSets)).artLayers.item(len(nArtLayers))

    def applyCrystallize(cellSize):
        cellSizeID = ps.app.CharIDToTypeID("ClSz")
        eventCrystallizeID = ps.app.CharIDToTypeID("Crst")

        filterDescriptor = ps.ActionDescriptor
        filterDescriptor.putInteger(cellSizeID, cellSize)
Exemplo n.º 16
0
"""A trim example."""

from photoshop import Session

import examples._psd_files as psd  # Import from examples.

PSD_FILE = psd.get_psd_files()
example_file = PSD_FILE["trim.psd"]
with Session(example_file, action="open") as ps:
    ps.active_document.trim(ps.TrimType.TopLeftPixel, True, True, True, True)
Exemplo n.º 17
0
from photoshop import Session


def do_something(photoshop_api):
    print(photoshop_api.active_document)
    print("Do something.")


with Session(callback=do_something) as ps:
    ps.echo(ps.active_document.name)
    ps.alert(ps.active_document.name)
to execute the Crystallize filter.
In order to find all the IDs, see https://helpx.adobe.com/photoshop/kb/downloadable-plugins-and-content.html#ScriptingListenerplugin
This blog here explains what a script listener is http://blogs.adobe.com/crawlspace/2006/05/installing_and_1.html

References:
    https://github.com/lohriialo/photoshop-scripting-python/blob/master/ApplyCrystallizeFilterAction.py

"""

from photoshop import Session

import examples._psd_files as psd  # Import from examples.

PSD_FILE = psd.get_psd_files()

with Session(PSD_FILE["layer_comps.psd"], "open") as ps:
    nLayerSets = ps.active_document.layerSets
    print(len(nLayerSets))
    nArtLayers = ps.active_document.layerSets.item(len(nLayerSets)).artLayers

    # get the last layer in LayerSets
    ps.active_document.activeLayer = ps.active_document.layerSets.item(
        len(nLayerSets)
    ).artLayers.item(len(nArtLayers))

    def applyCrystallize(cellSize):
        cellSizeID = ps.app.CharIDToTypeID("ClSz")
        eventCrystallizeID = ps.app.CharIDToTypeID("Crst")

        filterDescriptor = ps.ActionDescriptor
        filterDescriptor.putInteger(cellSizeID, cellSize)
Exemplo n.º 19
0
"""Action for duplicate current active document."""
from photoshop import Session

with Session(action="document_duplicate") as ps:
    ps.echo(ps.active_document.name)
Exemplo n.º 20
0
import photoshop.api as ps
from photoshop import Session

# style 1
app = ps.Application()
app.load("your/psd/or/psb/file_path.psd")

# style 2
with Session("your/psd/or/psb/file_path.psd", action="open") as ps:
    ps.echo(ps.active_document.name)
Exemplo n.º 21
0
- Open template.
- Update info.
- Save as jpg.
- Close current document.

"""

import os
from datetime import datetime

from photoshop import Session

import examples._psd_files as psd  # Import from examples.

PSD_FILE = psd.get_psd_files()
slate_template = PSD_FILE["slate_template.psd"]
with Session(slate_template, action="open", auto_close=True) as ps:
    layer_set = ps.active_document.layerSets.getByName("template")

    data = {
        "project name": "test_project",
        "datetime": datetime.today().strftime("%Y-%m-%d"),
    }
    for layer in layer_set.layers:
        if layer.kind == "TextLayer":
            layer.textItem.contents = data[layer.textItem.contents.strip()]

    jpg_file = "d:/photoshop_slate.jpg"
    ps.active_document.saveAs(jpg_file, ps.JPEGSaveOptions())
    os.startfile(jpg_file)
"""This script demonstrates how you can use the action manager to execute the
Emboss filter.

References:
    https://github.com/lohriialo/photoshop-scripting-python/blob/master/SmartSharpen.py

"""

from photoshop import Session

import examples._psd_files as psd  # Import from examples.

PSD_FILE = psd.get_psd_files()
file_path = PSD_FILE["layer_comps.psd"]

with Session(file_path, action="open") as ps:

    def SmartSharpen(inAmount, inRadius, inNoise):
        idsmart_sharpen_id = ps.app.stringIDToTypeID(ps.EventID.SmartSharpen)
        desc37 = ps.ActionDescriptor()

        idpresetKind = ps.app.stringIDToTypeID(ps.EventID.PresetKind)
        idpresetKindType = ps.app.stringIDToTypeID(ps.EventID.PresetKindType)
        idpresetKindCustom = ps.app.stringIDToTypeID(
            ps.EventID.PresetKindCustom)
        desc37.putEnumerated(idpresetKind, idpresetKindType,
                             idpresetKindCustom)
        idAmnt = ps.app.charIDToTypeID("Amnt")
        idPrc = ps.app.charIDToTypeID("Rds ")
        desc37.putUnitDouble(idAmnt, idPrc, inAmount)
Exemplo n.º 23
0
"""Add slate information dynamically."""

import os
from datetime import datetime
from tempfile import mkdtemp

from photoshop import Session

import examples._psd_files as psd  # Import from examples.

PSD_FILE = psd.get_psd_files()
file_path = PSD_FILE["slate_template.psd"]

with Session(file_path, action="open", auto_close=True) as ps:
    layer_set = ps.active_document.layerSets.getByName("template")
    data = {
        "project name": "test_project",
        "datetime": datetime.today().strftime("%Y-%m-%d"),
    }
    for layer in layer_set.layers:
        if layer.kind == ps.LayerKind.TextLayer:
            layer.textItem.contents = data[layer.textItem.contents.strip()]

    jpg_file = os.path.join(mkdtemp("photoshop-python-api"), "slate.jpg")
    ps.active_document.saveAs(jpg_file, ps.JPEGSaveOptions())
    os.startfile(jpg_file)
Exemplo n.º 24
0
class TestTextItem:
    """Test the solidColor."""

    # pylint: disable=attribute-defined-outside-init
    @pytest.fixture(autouse=True)
    def setup(self, psd_file):
        """Setup for current test."""
        self.session = Session(file_path=psd_file("textitem"),
                               action="open",
                               auto_close=True)
        self.session.run_action()
        doc = self.session.active_document
        layer = doc.activeLayer
        self.text_item = layer.textItem()  # -> TextItem
        yield
        # self.session.close()

    def test_alternateLigatures(self):
        assert self.text_item.alternateLigatures == 0

    def test_antiAliasMethod(self):
        assert self.text_item.antiAliasMethod == 3

    def test_autoKerning(self):
        assert self.text_item.autoKerning == 2

    def test_autoLeadingAmount(self):
        assert self.text_item.autoLeadingAmount == 120.00000476837158

    def test_set_autoLeadingAmount(self):
        self.text_item.autoLeadingAmount = 20
        assert self.text_item.autoLeadingAmount == 20.000000298023224

    def test_baseline_shift(self):
        assert self.text_item.baselineShift == 0.0

    def test_fauxBold(self):
        assert not self.text_item.fauxBold

    def test_set_fauxBold(self):
        assert not self.text_item.fauxBold
        self.text_item.fauxBold = True
        assert self.text_item.fauxBold

    def test_fauxItalic(self):
        assert not self.text_item.fauxItalic

    def test_firstLineIndent(self):
        assert self.text_item.firstLineIndent == 0.0

    def test_get_font(self):
        assert self.text_item.font == "ArialMT"

    def test_set_font(self):
        self.text_item.font = "AdobeThai-Regular"
        assert self.text_item.font == "AdobeThai-Regular"

    def test_hangingPunctuation(self):
        assert not self.text_item.hangingPunctuation

    def test_hyphenateAfterFirst(self):
        assert self.text_item.hyphenateAfterFirst == 2

    def test_justification(self):
        assert self.text_item.justification == 1

    def test_set_justification(self):
        self.text_item.justification = 2
        assert self.text_item.justification == 2

    def test_kind(self):
        assert self.text_item.kind == 1

    def test_set_kind(self):
        self.text_item.kind = TextType.ParagraphText
        assert self.text_item.kind == 2
        assert self.text_item.kind == TextType.ParagraphText

    def test_noBreak(self):
        assert not self.text_item.noBreak

    def test_position(self):
        assert self.text_item.position == (5.0, 57.0)

    def test_size(self):
        assert self.text_item.size == 18.0

    def test_change_size(self):
        self.text_item.size = 20
        assert self.text_item.size == 20.0
Exemplo n.º 25
0
import os
from photoshop import Session

with Session(auto_close=True) as ps:
    orig_name = ps.active_document.name
    width_str = ps.active_document.width
    height_str = ps.active_document.height
    thumb_name = f'{orig_name}_tumb'
    index = width_str / 1248

    thumb_width = int(width_str / index)

    thumb_height = int(height_str / index)

    thumb_doc = ps.active_document.duplicate(thumb_name)
    thumb_doc.resizeImage(thumb_width, thumb_height - 100)
    thumb_file = 'd:/thumb.jpg'
    thumb_doc.saveAs(thumb_file, ps.JPEGSaveOptions(), asCopy=True)
    thumb_doc.close()
    os.startfile(thumb_file)
"""This script demonstrates how you can use the action manager to execute the
Emboss filter.

References:
    https://github.com/lohriialo/photoshop-scripting-python/blob/master/SmartSharpen.py

"""

import os
from photoshop import Session

fileName = os.path.join(os.path.dirname(__file__), 'layer_comps.psd')

with Session(fileName) as ps:

    def SmartSharpen(inAmount, inRadius, inNoise):
        idsmart_sharpen_id = ps.app.stringIDToTypeID(ps.smartSharpen)
        desc37 = ps.ActionDescriptor()

        idpresetKind = ps.app.stringIDToTypeID(ps.presetKind)
        idpresetKindType = ps.app.stringIDToTypeID(ps.presetKindType)
        idpresetKindCustom = ps.app.stringIDToTypeID(ps.presetKindCustom)
        desc37.putEnumerated(idpresetKind, idpresetKindType,
                             idpresetKindCustom)

        idAmnt = ps.app.charIDToTypeID(ps.AMNT)
        idPrc = ps.app.charIDToTypeID(ps.RDS)
        desc37.putUnitDouble(idAmnt, idPrc, inAmount)

        idRds = ps.app.charIDToTypeID(ps.RDS)
        idPxl = ps.app.charIDToTypeID(ps.PX1)
Exemplo n.º 27
0
"""Change the color of the background and foreground."""
from photoshop import Session

with Session() as ps:
    foregroundColor = ps.SolidColor()
    foregroundColor.rgb.red = 255
    foregroundColor.rgb.green = 0
    foregroundColor.rgb.blue = 0
    ps.app.foregroundColor = foregroundColor

    backgroundColor = ps.SolidColor()
    backgroundColor.rgb.red = 0
    backgroundColor.rgb.green = 0
    backgroundColor.rgb.blue = 0
    ps.app.backgroundColor = backgroundColor
 def setup(self):
     self.session = Session()
     self.solid_color = self.session.SolidColor()