Using FileSaveAs and renaming a file according to a pattern

Moderator: Kathy_9

BV7
Posts: 5
Joined: Thu Jul 29, 2021 8:55 am
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit

Using FileSaveAs and renaming a file according to a pattern

Post by BV7 »

I'm trying to automate some image editing tasks on PaintShop Pro.

Simply put, I want to manually load an image into PSP from its current location and then run a script on the image to resize, then canvas resize and finally save the resulting file with a new name in its original location.

I've achieved most of that with this script ...

from PSPApp import *

def ScriptProperties():
return {
'Author': u'',
'Copyright': u'',
'Description': u'',
'Host': u'PaintShop Pro',
'Host Version': u'21.00'
}

def Do(Environment):
path = App.TargetDocument.Name.rstrip(App.TargetDocument.Title)
filename = path + "#" + App.TargetDocument.Title
# EnableOptimizedScriptUndo
App.Do( Environment, 'EnableOptimizedScriptUndo', {
'GeneralSettings': {
'ExecutionMode': App.Constants.ExecutionMode.Default,
'AutoActionMode': App.Constants.AutoActionMode.Match,
'Version': ((21,0,0),1)
}
})

# Resize
App.Do( Environment, 'Resize', {
'AspectRatio': 0.997183,
'CurrentDimensionUnits': App.Constants.UnitsOfMeasure.Pixels,
'CurrentResolutionUnits': App.Constants.ResolutionUnits.PixelsPerIn,
'Height': 251,
'MaintainAspectRatio': True,
'Resample': True,
'ResampleType': App.Constants.ResampleType.Bicubic,
'ResizeAllLayers': True,
'Resolution': 499,
'Width': 250,
'SharpnessValue': 50,
'AdvancedMode': True,
'ResizeType': 0,
'OneSide_Type': 0,
'OneSide_LongWidth': 657,
'OneSide_ShortHeight': 655,
'OneSide_Unit': App.Constants.UnitsOfMeasure.Pixels,
'OneSide_Active': 0,
'GeneralSettings': {
'ExecutionMode': App.Constants.ExecutionMode.Default,
'AutoActionMode': App.Constants.AutoActionMode.Match,
'Version': ((21,0,0),1)
}
})

# ResizeCanvas
App.Do( Environment, 'ResizeCanvas', {
'AspectRatio': 0.996016,
'FillColor': (9,7,10),
'HoriPlace': App.Constants.HorizontalType.Center,
'MaintainAspect': False,
'NewDimUnits': App.Constants.UnitsOfMeasure.Pixels,
'NewHeight': 250,
'NewWidth': 250,
'PlaceBottom': -1,
'PlaceLeft': 0,
'PlaceRight': 0,
'PlaceTop': 0,
'VertPlace': App.Constants.VerticalType.Center,
'GeneralSettings': {
'ExecutionMode': App.Constants.ExecutionMode.Default,
'AutoActionMode': App.Constants.AutoActionMode.Match,
'Version': ((21,0,0),1)
}
})

# FileSaveAs
App.Do( Environment, 'FileSaveAs', {
'Encoding': {
'JPG': {
'Variant': App.Constants.JpegFormat.Lossless,
'CompressionFactor': 0,
'ChromaSubSampling': App.Constants.ChromaSubSampling.YCC_1x1_1x1_1x1,
'EXIF': True,
'EmbedJPGICC': True
}
},
'FileName': filename,
'FileFormat': App.Constants.FileFormat.JPG,
'FormatDesc': u'JPG JPEG ',
'WorkingMode': 0,
'GeneralSettings': {
'ExecutionMode': App.Constants.ExecutionMode.Default,
'AutoActionMode': App.Constants.AutoActionMode.Match,
'Version': ((23,0,0),1)
},
'DefaultProperties': []
})

The final step which would make the script ideal for what I'm trying to do, would be if I could find a way the rename the file to be saved according to a pattern. In the above script I am already adding "#" to the front of the original filename but I would also like to remove any numeric characters from the end of the original filename. These numeric characters at the end of the original filenames can be anything from 1 to 5 digits long. For example, I would like Landscape1.jpg or Landscape22.jpg or Landscape333.jpg etc. to be saved as #Landscape.jpg ... Any ideas? Is there something I could do with re-sub and isnumeric() ? I'm very much the novice with scripting so any help would be gratefully received!
cosmicDread
Posts: 42
Joined: Fri Aug 26, 2016 7:10 am
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit
motherboard: MSI MPG Z390 Gaming PRO
processor: Intel Core i9-9900K
ram: 32 GB
Video Card: GeForce GTX 1080 Ti
Hard_Drive_Capacity: 6 TB
Monitor/Display Make & Model: Acer Predator X34
Corel programs: PaintShop X5, X6, X8, X9, '18, '19, '20
Location: Lake Havasu City, Arizona, USA

Re: Using FileSaveAs and renaming a file according to a pattern

Post by cosmicDread »

This code removes the digits from the end of a file name. I have only
tested this in the Python 2.7 console. You may need to adjust the code.

Code: Select all

import os

# Remove digits from the end of the file name.
#
# Get file 'name' without the extension or path component:
path_pair = os.path.split(filename)
name_pair = os.path.splitext(path_pair[1])
name = name_pair[0]

# Do loop until the last character is not a digit:
while 1:
	# Exit the loop if 'name' is at its shortest possible length:
	if len(name) == 1:
		break

	# Is the last character a number?
	if name[-1].isdigit():
		# Remove character:
		name = name[:-1]
	else:
		# no more characters:
		break

# Recombine 'filename':
filename = os.path.join(path_pair[0], name + name_pair[1])
A warning: You may end up over-writing files after renaming, as the new filename may already exist.
Charles
When the majority of the people on Earth are wanting the Galactic Federation to show themselves, then they will.
BV7
Posts: 5
Joined: Thu Jul 29, 2021 8:55 am
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit

Re: Using FileSaveAs and renaming a file according to a pattern

Post by BV7 »

Great ... thanks for your help! I'll give it a try now.
BV7
Posts: 5
Joined: Thu Jul 29, 2021 8:55 am
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit

Re: Using FileSaveAs and renaming a file according to a pattern

Post by BV7 »

Again, many thanks! Your script works perfectly. I'm just not sure how to integrate it into mine.
I've tried a few iterations without success ... could I prevail on you to give me a few pointers on how to add this?
cosmicDread
Posts: 42
Joined: Fri Aug 26, 2016 7:10 am
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit
motherboard: MSI MPG Z390 Gaming PRO
processor: Intel Core i9-9900K
ram: 32 GB
Video Card: GeForce GTX 1080 Ti
Hard_Drive_Capacity: 6 TB
Monitor/Display Make & Model: Acer Predator X34
Corel programs: PaintShop X5, X6, X8, X9, '18, '19, '20
Location: Lake Havasu City, Arizona, USA

Re: Using FileSaveAs and renaming a file according to a pattern

Post by cosmicDread »

I put this code block into the header of your code, and tested it. This block replaces your code up to the Resize function. I'm using spaces and not tabs for the indentation, so your code must do the same. Have you tried opening the Script Window to check for errors?

Code: Select all

from PSPApp import *
import os


def ScriptProperties():
    return {
        'Author': u'',
        'Copyright': u'',
        'Description': u'',
        'Host': u'PaintShop Pro',
        'Host Version': u'21.00'
    }


def Do(Environment):
    path = App.TargetDocument.Name.rstrip(App.TargetDocument.Title)

    App.Do(
        Environment, 'EnableOptimizedScriptUndo', {
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Default,
                'AutoActionMode': App.Constants.AutoActionMode.Match
            }
        }
    )

    # Remove digits from the end of the file name.
    #
    # Get file 'name' without the extension or path component:
    name_pair = os.path.splitext(App.TargetDocument.Title)

    # Insert the pattern character into the file name:
    name = "#" + name_pair[0]

    # Do loop until the last character is not a digit:
    while 1:
        # Exit the loop if 'name' is at its shortest possible length:
        if len(name) == 1:
            break

        # Is the last character a number?
        if name[-1].isdigit():
            # Remove character:
            name = name[:-1]

        else:
            # no more characters:
            break

    # Recombine 'filename':
    filename = os.path.join(path, name + name_pair[1])

    # Print 'filename' to the Script Output window:
    print "File name:\t", filename
Charles
When the majority of the people on Earth are wanting the Galactic Federation to show themselves, then they will.
BV7
Posts: 5
Joined: Thu Jul 29, 2021 8:55 am
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit

Re: Using FileSaveAs and renaming a file according to a pattern

Post by BV7 »

Thanks again for spending time to look at this. i put your code into the header as suggested and i use spaces also. It ran without error but the resulting files still had all the numeric endings showing
cosmicDread
Posts: 42
Joined: Fri Aug 26, 2016 7:10 am
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit
motherboard: MSI MPG Z390 Gaming PRO
processor: Intel Core i9-9900K
ram: 32 GB
Video Card: GeForce GTX 1080 Ti
Hard_Drive_Capacity: 6 TB
Monitor/Display Make & Model: Acer Predator X34
Corel programs: PaintShop X5, X6, X8, X9, '18, '19, '20
Location: Lake Havasu City, Arizona, USA

Re: Using FileSaveAs and renaming a file according to a pattern

Post by cosmicDread »

I tested this code PSP X9 and PSP 2020. It worked in both programs.
The code is resizing the image and saving it to the same directory as
it was opened but without a numeric postfix. It is also inserting a
pattern character as a prefix to the file name.

A file named c:\pictures\'my image file 0123.jpg' is renamed to:
'c:\pictures\#my image file.jpg'

If the code isn't working then there may be some problem with OS enforced user privileges.

You are running the script from a PSP recognized Trusted folder right?

Charles

Code: Select all

from PSPApp import *
import os


# Resize canvas and save an image without a numeric file name postfix,
# and insert a pattern character into the prefix of the file name.


def ScriptProperties():
    """PSP X9"""
    return {
        'Author': u'',
        'Copyright': u'',
        'Description': u'',
        'Host': u'PaintShop Pro',
        'Host Version': u'19.00'
    }


def Do(Environment):
    path = App.TargetDocument.Name.rstrip(App.TargetDocument.Title)

    App.Do(
        Environment,
        'EnableOptimizedScriptUndo', {
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Default,
                'AutoActionMode': App.Constants.AutoActionMode.Match
            }
        }
    )

    # Remove numeric digits from the end of the file name.
    #
    # Get file 'name' without the extension or path component:
    name_pair = os.path.splitext(App.TargetDocument.Title)

    # Insert the pattern character into the file name:
    name = "#" + name_pair[0]

    # Do loop until the last character is not a digit:
    while 1:
        # Is the last character a number?
        if name[-1].isdigit():
            # Remove character:
            name = name[:-1]

        else:
            # no more trailing numbers:
            break

    # Recombine 'filename':
    filename = os.path.join(path, name.strip() + name_pair[1])

    # print filename to the Script Output window:
    print "File name:\t", filename
    
    App.Do(
        Environment,
        'ResizeCanvas', {
            'AspectRatio': 0.996016,
            'FillColor': (9,7,10),
            'HoriPlace': App.Constants.HorizontalType.Center,
            'MaintainAspect': False,
            'NewDimUnits': App.Constants.UnitsOfMeasure.Pixels,
            'NewHeight': 250,
            'NewWidth': 250,
            'PlaceBottom': -1,
            'PlaceLeft': 0,
            'PlaceRight': 0,
            'PlaceTop': 0,
            'VertPlace': App.Constants.VerticalType.Center,
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Default,
                'AutoActionMode': App.Constants.AutoActionMode.Match
            }
        }
    )
    App.Do(Environment,
        'FileSaveAs', {
            'Encoding': {
            'JPG': {
                'Variant': App.Constants.JpegFormat.Lossless,
                'CompressionFactor': 0,
                'ChromaSubSampling': App.Constants.ChromaSubSampling.YCC_1x1_1x1_1x1,
                'EXIF': True,
                'EmbedJPGICC': True
            }
        },
        'FileName': filename,
        'FileFormat': App.Constants.FileFormat.JPG,
        'FormatDesc': u'JPG JPEG ',
        'WorkingMode': 0,
        'GeneralSettings': {
            'ExecutionMode': App.Constants.ExecutionMode.Default,
            'AutoActionMode': App.Constants.AutoActionMode.Match
        },
        'DefaultProperties': []
    })
When the majority of the people on Earth are wanting the Galactic Federation to show themselves, then they will.
BV7
Posts: 5
Joined: Thu Jul 29, 2021 8:55 am
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit

Re: Using FileSaveAs and renaming a file according to a pattern

Post by BV7 »

Thanks so much! it works perfectly. (This issue before was my own placement of the additional code).
I'm very grateful for your help!