Skip to main content
Participant
May 8, 2023
Answered

Trying to script with AI, need some review from someone who knows what they're doing

  • May 8, 2023
  • 2 replies
  • 2989 views

Hey there, 

I'm new to photoshop and scripting and have been trying to build a script with ChatGPT that does the following: 
Choose a folder in which all png files will be resized to 3600x3600 and saved as jpg files in an automatically created folder within the source folder that has the same name +jpg. 

I've been troubleshooting so many times but chatgpt is just turning in circles. 

Thanks for your help, here's the script: 

import os
import subprocess
import tkinter as tk
from tkinter import filedialog

# Create a Tkinter root window
root = tk.Tk()
root.withdraw()

# Prompt the user to select the source folder interactively
source_folder_path = filedialog.askdirectory(title="Select Source Folder")

# Create a new folder for saving the JPG files
jpg_folder_name = os.path.basename(source_folder_path) + "_jpg"
jpg_folder_path = os.path.join(source_folder_path, jpg_folder_name)
os.makedirs(jpg_folder_path, exist_ok=True)

# Loop through each PNG file in the source folder
for filename in os.listdir(source_folder_path😞
if filename.endswith(".png"😞
# Set the full path to the PNG file
png_path = os.path.join(source_folder_path, filename)
 
# Set the full path to the JPG file
jpg_filename = os.path.splitext(filename)[0] + ".jpg"
jpg_path = os.path.join(jpg_folder_path, jpg_filename)
 
# Build the AppleScript command to open the PNG file in Photoshop
open_command = 'tell application "Adobe Photoshop 2023"\nopen POSIX file "{}"\nend tell'.format(png_path)
 
# Build the AppleScript command to resize the document to 3600x3600 pixels
resize_command = 'tell application "Adobe Photoshop 2023"\nresize image width 3600 height 3600 resolution 300 resample method bicubicSharper\nend tell'
 
# Build the AppleScript command to save the document as a JPG file with options
save_command = 'tell application "Adobe Photoshop 2023"\nactivate\ntell front document\nsave as POSIX file "{}" as JPEG with options {{class:JPEG save options, save options: {{class:JPEG save options, quality:10}}}}\nend tell\nend tell'.format(jpg_path)
 
# Run the AppleScript commands using the "osascript" command-line tool
subprocess.call(['osascript', '-e', open_command])
subprocess.call(['osascript', '-e', resize_command])
subprocess.call(['osascript', '-e', save_command])


Have a great day
This topic has been closed for replies.
Correct answer Stephen Marsh

@AsanteNuru 

 

Here is a JS version:

 

/*
Upscale Folder of 1024px PNG Images to 3600px JPEG.jsx
v1.0 - 9th May 2023, Stephen Marsh
https://community.adobe.com/t5/photoshop-ecosystem-discussions/trying-to-script-with-ai-need-some-review-from-someone-who-knows-what-they-re-doing/td-p/13779500
*/

#target photoshop

(function () {

    if (!app.documents.length) {

        var srcFolder = Folder.selectDialog("Select the PNG source folder");
        if (srcFolder === null) {
            return;
        }

        var jpgFolderPath = srcFolder.fsName + "/" + srcFolder.name + "_jpg";
        var jpgFolder = new Folder(jpgFolderPath);
        if (!jpgFolder.exists) {
            jpgFolder.create();
        }

        var srcList = srcFolder.getFiles(/\.png$/i);
        srcList.sort();

        var validateList = (srcList.length > 0);
        if (validateList === false) {
            alert("Script cancelled as there are no PNG files!");
            return;
        }

        var fileCounter = 0;

        while (srcList.length) {
            for (var i = 0; i < 1; i++) {
                try {
                    app.open(srcList.pop());
                    activeDocument.resizeImage(UnitValue(3600, "px"), undefined, null, ResampleMethod.BICUBICSHARPER);
                    var jpgOptions = new JPEGSaveOptions();
                    jpgOptions.formatOptions = FormatOptions.STANDARDBASELINE;
                    jpgOptions.embedColorProfile = true;
                    jpgOptions.matte = MatteType.NONE;
                    jpgOptions.quality = 10;
                    var jpgSave = new File(jpgFolderPath + "/" + activeDocument.name.replace(/\.[^\.]+$/, '') + ".jpg");
                    activeDocument.saveAs(jpgSave, jpgOptions, true, Extension.LOWERCASE);
                    activeDocument.close(SaveOptions.DONOTSAVECHANGES);
                } catch (e) {}
            }
            fileCounter++;
        }

        app.beep();
        alert('Script completed!' + '\n' + fileCounter + ' JPEG files saved to:' + '\n' + jpgFolder.fsName);

    } else {
        alert('Please close all open documents before running this script!');
    }

})();

 

EDIT: Image Processor Pro can do all of this, however, one has to create the sub-folder name manually:

 

https://sourceforge.net/projects/ps-scripts/files/Image%20Processor%20Pro/v3_2%20betas/

 

2 replies

Stephen Marsh
Community Expert
Stephen MarshCommunity ExpertCorrect answer
Community Expert
May 9, 2023

@AsanteNuru 

 

Here is a JS version:

 

/*
Upscale Folder of 1024px PNG Images to 3600px JPEG.jsx
v1.0 - 9th May 2023, Stephen Marsh
https://community.adobe.com/t5/photoshop-ecosystem-discussions/trying-to-script-with-ai-need-some-review-from-someone-who-knows-what-they-re-doing/td-p/13779500
*/

#target photoshop

(function () {

    if (!app.documents.length) {

        var srcFolder = Folder.selectDialog("Select the PNG source folder");
        if (srcFolder === null) {
            return;
        }

        var jpgFolderPath = srcFolder.fsName + "/" + srcFolder.name + "_jpg";
        var jpgFolder = new Folder(jpgFolderPath);
        if (!jpgFolder.exists) {
            jpgFolder.create();
        }

        var srcList = srcFolder.getFiles(/\.png$/i);
        srcList.sort();

        var validateList = (srcList.length > 0);
        if (validateList === false) {
            alert("Script cancelled as there are no PNG files!");
            return;
        }

        var fileCounter = 0;

        while (srcList.length) {
            for (var i = 0; i < 1; i++) {
                try {
                    app.open(srcList.pop());
                    activeDocument.resizeImage(UnitValue(3600, "px"), undefined, null, ResampleMethod.BICUBICSHARPER);
                    var jpgOptions = new JPEGSaveOptions();
                    jpgOptions.formatOptions = FormatOptions.STANDARDBASELINE;
                    jpgOptions.embedColorProfile = true;
                    jpgOptions.matte = MatteType.NONE;
                    jpgOptions.quality = 10;
                    var jpgSave = new File(jpgFolderPath + "/" + activeDocument.name.replace(/\.[^\.]+$/, '') + ".jpg");
                    activeDocument.saveAs(jpgSave, jpgOptions, true, Extension.LOWERCASE);
                    activeDocument.close(SaveOptions.DONOTSAVECHANGES);
                } catch (e) {}
            }
            fileCounter++;
        }

        app.beep();
        alert('Script completed!' + '\n' + fileCounter + ' JPEG files saved to:' + '\n' + jpgFolder.fsName);

    } else {
        alert('Please close all open documents before running this script!');
    }

})();

 

EDIT: Image Processor Pro can do all of this, however, one has to create the sub-folder name manually:

 

https://sourceforge.net/projects/ps-scripts/files/Image%20Processor%20Pro/v3_2%20betas/

 

Participant
May 10, 2023

wow @Stephen Marsh you're an angel. Thanks a big bunch for your help. Will stick do JS in the future! Gonna try it now 

Stephen Marsh
Community Expert
Community Expert
May 9, 2023

@AsanteNuru – What scripting language is that?

 

The forum software has incorrectly reformated your code with smilies, you need to use the </> button to insert your code:

 

// Like this...

 

 Are the source files larger than 3600x3600px, or smaller?

 

Are the source files square, or are they a mixture of landscape/portrait/square orientations?

 

If the backgrounds are not square, do you wish to "pad out" the canvas? If so what colour will be used as the canvas colour (as JPEG can't support transparency)? Or would you use content aware fill rather than a flat colour? Or would the canvas be cropped to square?

 

If you use the forum search feature, you will find many topics with either Actions or JavaScript code for processing square images.

 

Participant
May 9, 2023

@Stephen Marsh Hey Stephen and thanks for getting back to me. 
Here's the code correctly.

To answer your questions. The source files are 1024x1024 and all square. 
Thanks for the pointer, I will have a look around the forum - would still love if someone can maybe identify the error in this bit of code. 

 

 

import os
import subprocess
import tkinter as tk
from tkinter import filedialog

# Create a Tkinter root window
root = tk.Tk()
root.withdraw()

# Prompt the user to select the source folder interactively
source_folder_path = filedialog.askdirectory(title="Select Source Folder")

# Create a new folder for saving the JPG files
jpg_folder_name = os.path.basename(source_folder_path) + "_jpg"
jpg_folder_path = os.path.join(source_folder_path, jpg_folder_name)
os.makedirs(jpg_folder_path, exist_ok=True)

# Loop through each PNG file in the source folder
for filename in os.listdir(source_folder_path):
    if filename.endswith(".png"):
        # Set the full path to the PNG file
        png_path = os.path.join(source_folder_path, filename)
        
        # Set the full path to the JPG file
        jpg_filename = os.path.splitext(filename)[0] + ".jpg"
        jpg_path = os.path.join(jpg_folder_path, jpg_filename)
        
        # Build the AppleScript command to open the PNG file in Photoshop
        open_command = 'tell application "Adobe Photoshop 2023"\nopen POSIX file "{}"\nend tell'.format(png_path)
        
        # Build the AppleScript command to resize the document to 3600x3600 pixels
        resize_command = 'tell application "Adobe Photoshop 2023"\nresize image width 3600 height 3600 resolution 300 resample method bicubicSharper\nend tell'
        
        # Build the AppleScript command to save the document as a JPG file with options
        save_command = 'tell application "Adobe Photoshop 2023"\nactivate\ntell front document\nsave as POSIX file "{}" as JPEG with options {{class:JPEG save options, save options: {{class:JPEG save options, quality:10}}}}\nend tell\nend tell'.format(jpg_path)
            
        # Run the AppleScript commands using the "osascript" command-line tool
        subprocess.call(['osascript', '-e', open_command])
        subprocess.call(['osascript', '-e', resize_command])
        subprocess.call(['osascript', '-e', save_command])

Participant
May 9, 2023

P.S. This is in python being run by an applescript as a .app