• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
1

Editing t-shirt mockup with multiple designs script

Community Beginner ,
May 12, 2020 May 12, 2020

Copy link to clipboard

Copied

Hi,

I have a T-shirt mockup with one psb. I have 100s of png designs which i want to edit in this mockup and save the output file as png. Can anyone provide me the script for this?

 

I am working on windows.

 

Capture.PNG

TOPICS
Actions and scripting , Windows

Views

5.7K

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Adobe
Community Expert ,
May 12, 2020 May 12, 2020

Copy link to clipboard

Copied

I'd start here with a forum search, t-shirt and phone cases are the most commonly requested, there must be 50 or so topic threads. 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
May 13, 2020 May 13, 2020

Copy link to clipboard

Copied

I searched a lot but either the script was not working or ended up with the scripts of different requirements. I would appreciate if you could help me out.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
May 13, 2020 May 13, 2020

Copy link to clipboard

Copied

Here are some more to look into:

 

https://community.adobe.com/t5/photoshop/editing-t-shirt-mockup-with-multiple-designs-script/m-p/111...

https://community.adobe.com/t5/photoshop/t-shirt-design-saving-designs-on-my-t-shirt-mockups-each-co...

https://community.adobe.com/t5/photoshop/how-to-use-a-t-shirt-mockup-template/m-p/9292921?search-act...

https://community.adobe.com/t5/photoshop/batch-replace-smart-layer-amp-save-as-jpg-using-s-l-name/m-...

https://community.adobe.com/t5/photoshop/how-do-i-place-a-design-on-a-t-shirt-mockup/m-p/9471458?sea...

https://community.adobe.com/t5/photoshop/script-that-can-automate-t-shirt-variation-designs/m-p/9744...

https://community.adobe.com/t5/photoshop/photoshop-action-that-can-autosave-50-design/m-p/8375575?se...

https://community.adobe.com/t5/photoshop/batch-processing-a-folder-of-designs-onto-a-folder-full-of-...

https://community.adobe.com/t5/photoshop/automating-product-image-creation/m-p/10621181?search-actio...

https://community.adobe.com/t5/photoshop/how-to-batch-automate-a-batch-automation/m-p/10272800?searc...

https://community.adobe.com/t5/photoshop/batch-replace-smart-objects-in-mockup-file/m-p/9661738?sear...

https://community.adobe.com/t5/photoshop-elements/how-to-create-realistic-tshirt-design-mockup/m-p/1...

https://community.adobe.com/t5/photoshop/script-for-phone-case-mockup/m-p/10637699?search-action-id=...

https://community.adobe.com/t5/photoshop/script-to-place-logos-in-diffrent-phones-cases-in-photshop/...

https://community.adobe.com/t5/photoshop/script-for-phone-case-mockup/m-p/10637699?search-action-id=...

https://community.adobe.com/t5/photoshop/creating-mockups-with-smart-object/m-p/10319025?search-acti...

https://community.adobe.com/t5/photoshop/batch-generation-of-images/m-p/11088426?search-action-id=60...

https://community.adobe.com/t5/photoshop/replace-my-design-in-all-mockups-smartobjects/m-p/8968591?s...

https://community.adobe.com/t5/photoshop/replace-my-design-in-all-mockups-with-2-smartobjects/m-p/91...

https://community.adobe.com/t5/photoshop/photoshop-script-for-multiple-mockups/m-p/10214759?search-a...

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
May 13, 2020 May 13, 2020

Copy link to clipboard

Copied

JJMack's mockup templates may be all you need:

 

http://www.mouseprints.net/old/dpr/PhotoCollageToolkit.html

 

The forum would need to download examples to offer specific advice on your assets. Say 3 random samples of finished images and the PSD template and the PNG source files for starters. Otherwise it is a waste of time and effort.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
May 19, 2020 May 19, 2020

Copy link to clipboard

Copied

Thank you so so much. I got what I was looking for. There is just one small problem. My psd doesn't have a background so this script saves it with white background as it saves the output as jpg. Can't it export a png file with no background?

 

/* ==========================================================
// 2010 John J. McAssey (JJMack)
// ======================================================= */

// This script is supplied as is. It is provided as freeware.
// The author accepts no liability for any problems arising from its use.

// Image files and Template objects should have the same orientation close matching Aspect Ratios same
// ratio is even better. This script can try to edit smart objects and fit any size image the
// best as it can and even try to handle orientation miss matches.

/* Help Category note tag menu can be used to place script in automate menu
<javascriptresource>
<about>$$$/JavaScripts/BatchMockupTemplates/About=JJMack's Batch Mockup Templates.^r^rCopyright 2019 Mouseprints.^r^rBatch Update Top Layers Smart Object</about>
<category>JJMack's Collaga Script</category>
</javascriptresource>
*/

// enable double-clicking from Mac Finder or Windows Explorer
#target photoshop // this command only works in Photoshop CS2 and higher

// bring application forward for double-click events
app.bringToFront();

//////////////////////////////////
// SET-UP Preferences //
//////////////////////////////////
//@include "PCTpreferences.jsx"

var gVersion = 1.0;

// a global variable for the title of the dialog
// this string will also be used for the preferences file I write to disk
// Photoshop Install Directory/Presets/Image Processor/Image Processor.xml for example

var gScriptName = "BMTCollage";

// remember the dialog modes
var saveDialogMode = app.displayDialogs;
app.displayDialogs = DialogModes.NO;

try {
// make sure they are running Photoshop CS2
CheckVersion();

}
// Lot's of things can go wrong, Give a generic alert and see if they want the details
catch(e) {
if ( confirm("Sorry, something major happened and I can't continue! Would you like to see more info?" ) ) {
alert(e);
}
}


// Save the current preferences
var startRulerUnits = app.preferences.rulerUnits;
var startTypeUnits = app.preferences.typeUnits;
var startDisplayDialogs = app.displayDialogs;

// Set Photoshop to use pixels and display no dialogs
app.displayDialogs = DialogModes.NO;
app.preferences.rulerUnits = Units.PIXELS;
app.preferences.typeUnits = TypeUnits.PIXELS;

// Set the script location

var scriptLocation = findScript() + "0";

// Stuff I don't know much about
var strButtonSelect = localize("$$$/JavaScripts/ExportLayersToFiles/Select=Select...");
var strButtonBrowse = localize("$$$/JavaScripts/ExportLayersToFiles/Browse=Browse...");
var strAlertSpecifyTemplateFile = localize("$$$/JavaScripts/ExportLayersToFiles/SpecifyTemplateFile=Please specify a template file.");
var strAlertTemplateFileNotExist = localize("$$$/JavaScripts/ExportLayersToFiles/TemplateFileDoesNotExist=Template file does not exist.");
var strAlertSpecifyInputFolder = localize("$$$/JavaScripts/ExportLayersToFiles/SpecifyInputFolder=Please specify an input folder.");
var strAlertInputFolderNotExist = localize("$$$/JavaScripts/ExportLayersToFiles/InputFolderDoesNotExist=Input folder does not exist.");
var strAlertSpecifyDestination = localize("$$$/JavaScripts/ExportLayersToFiles/SpecifyDestination=Please specify an output folder.");
var strAlertDestinationNotExist = localize("$$$/JavaScripts/ExportLayersToFiles/DestionationDoesNotExist=Output folder does not exist.");

var exportInfo = new Object();
initExportInfo(exportInfo); // ??????

// define the dialog
// [left, top, right, bottom]
function createDialog(){

// Create an empty dialog window near the upper left of the screen
var dlg = new Window('dialog', 'Batch MockUp Templates');
dlg.frameLocation = [78, 100];

// Add a panel to hold title and 'message text' strings
dlg.msgPn0 = dlg.add('panel', undefined, 'Batch a Folder of Mockup Templates File');
dlg.msgPn0.orientation = "column";
dlg.msgPn0.alignChildren = 'Right';
// Add a panel to hold title and 'message text' strings
dlg.msgPn0.TemplateFile = dlg.msgPn0.add('group');
dlg.msgPn0.TemplateFile.orientation = "row";
dlg.msgPn0.etTemplateFile = dlg.msgPn0.add("edittext", undefined, exportInfo.destination.toString());
dlg.msgPn0.etTemplateFile.preferredSize.width = 550;
dlg.msgPn0.etTemplateFile.helpTip = "Select a Folder of Mockup Templates.";

dlg.msgPn0.btnSelect = dlg.msgPn0.add("button", undefined, strButtonBrowse);
dlg.msgPn0.btnSelect.helpTip = "Select Mockup Templates Folder to populate.";
dlg.msgPn0.btnSelect.onClick = function() {
var dir = Folder(dlg.msgPn0.etTemplateFile.text);
if (!dir.exists) var dir = Folder(templateFolder);

dlg.selTemplateFile = Folder.selectDialog(dlg.msgPn0.etTemplateFile.text , dir);
if ( dlg.selTemplateFile != null ) {
dlg.msgPn0.etTemplateFile.text = dlg.selTemplateFile.fsName;
}
//dlg.msgPn0.defaultElement.active = true;
}

// Add a panel to hold title and 'message text' strings
dlg.msgPn2 = dlg.add('panel', undefined, 'Objects Collection Folder');
dlg.msgPn2.orientation = "column";
dlg.msgPn2.alignChildren = 'Right';

dlg.msgPn2.InputFolder = dlg.msgPn2.add('group');
dlg.msgPn2.InputFolder.orientation = "row";
dlg.msgPn2.etInputFolder = dlg.msgPn2.add("edittext", undefined, exportInfo.destination.toString());
dlg.msgPn2.etInputFolder.preferredSize.width = 550;
dlg.msgPn2.etInputFolder.helpTip = "Choose a folder of images to process.";

dlg.msgPn2.btnBrowse = dlg.msgPn2.add("button", undefined, strButtonBrowse);
dlg.msgPn2.btnBrowse.helpTip = "Select the Collection of objects folders to process.";
dlg.msgPn2.btnBrowse.onClick = function() {
var defaultFolder = dlg.msgPn2.etInputFolder.text;
var testFolder = new Folder(dlg.msgPn2.etInputFolder.text);
if (!testFolder.exists) {
// defaultFolder = "~";
defaultFolder = imagePath;
}
// var selFolder = Folder.selectDialog(dlg.msgPn2.etInputFolder.text, defaultFolder);
dlg.selInputFolder = Folder.selectDialog(dlg.msgPn2.etInputFolder.text, defaultFolder);
if ( dlg.selInputFolder != null ) {
dlg.msgPn2.etInputFolder.text = dlg.selInputFolder.fsName;
}
//dlg.msgPn2.defaultElement.active = true;
}

// Add a panel to hold title and 'message text' strings
dlg.msgPn3 = dlg.add('panel', undefined, 'Output Folder');
dlg.msgPn3.orientation = "column";
dlg.msgPn3.alignChildren = 'Right';

dlg.msgPn3.Destination = dlg.msgPn3.add('group');
dlg.msgPn3.Destination.orientation = "row";
dlg.msgPn3.etDestination = dlg.msgPn3.add("edittext", undefined, exportInfo.destination.toString());
dlg.msgPn3.etDestination.preferredSize.width = 550;
dlg.msgPn3.etDestination.helpTip = "Choose a folder to export your collages to.";

dlg.msgPn3.btnBrowse = dlg.msgPn3.add("button", undefined, strButtonBrowse);
dlg.msgPn3.btnBrowse.helpTip = "Select a folder to export your collages to.";
dlg.msgPn3.btnBrowse.onClick = function() {
var defaultFolder = dlg.msgPn3.etDestination.text;
var testFolder = new Folder(dlg.msgPn3.etDestination.text);
if (!testFolder.exists) {
defaultFolder = "~";
}
dlg.selOutputFolder = Folder.selectDialog(dlg.msgPn3.etDestination.text, defaultFolder);
if ( dlg.selOutputFolder != null ) {
dlg.msgPn3.etDestination.text = dlg.selOutputFolder.fsName;
}
//dlg.msgPn3.defaultElement.active = true;
}

// Add a panel to hold title and 'message text' strings
dlg.msgPnl = dlg.add('panel', undefined, 'Options');
dlg.msgPnl.orientation = "column";
dlg.msgPnl.alignChildren = 'right';

dlg.msgPnl.EditImage = dlg.msgPnl.add('group');
dlg.msgPnl.EditImage.orientation = "row";
dlg.msgPnl.EditImage.alignment='left';
dlg.msgPnl.EditImage.st = dlg.msgPnl.EditImage.add('checkbox', undefined, 'Edit Smart Object');
dlg.msgPnl.EditImage.helpTip = "Edit Smart Object insead of replace content";

dlg.msgPnl.RotateForFit = dlg.msgPnl.add('group');
dlg.msgPnl.RotateForFit.orientation = "row";
dlg.msgPnl.RotateForFit.alignment='left';
dlg.msgPnl.RotateForFit.st = dlg.msgPnl.RotateForFit.add('checkbox', undefined, 'Rotate For Best Fit');
dlg.msgPnl.RotateForFit.helpTip = "Rotate For Best Fit.";

dlg.msgPnl.FitImage = dlg.msgPnl.add('group');
dlg.msgPnl.FitImage.orientation = "row";
dlg.msgPnl.FitImage.alignment='left';
dlg.msgPnl.FitImage.st = dlg.msgPnl.FitImage.add('checkbox', undefined, 'Fit Image');
dlg.msgPnl.FitImage.helpTip = "Fit Image not Fill Area.";

dlg.msgPnl.SavePSDfile = dlg.msgPnl.add('group');
dlg.msgPnl.SavePSDfile.orientation = "row";
dlg.msgPnl.SavePSDfile.alignment='left';
dlg.msgPnl.SavePSDfile.st = dlg.msgPnl.SavePSDfile.add('checkbox', undefined, 'Save PSD file');
dlg.msgPnl.SavePSDfile.helpTip = "Save a layered PSD file as well.";

// Add a panel with buttons to test parameters and
dlg.buttonPanel = dlg.add('panel', undefined);
dlg.buttonPanel.orientation = "row";
dlg.buttonPanel.cancelBtn = dlg.buttonPanel.add ('button', undefined,'Cancel');
dlg.buttonPanel.helpBtn = dlg.buttonPanel.add ('button', undefined,'Help');
dlg.buttonPanel.runBtn = dlg.buttonPanel.add ('button', undefined,'Create Mockup Collages');

return dlg;
}

var params = new Array();
params[''] = "";
params['InputFolder'] = "";
params['OutputFolder'] = "";
params['TemplateFile'] = "";

LoadParamsFromDisk( GetDefaultParamsFile(), params );

function initializeDialog (BMTCollage){
with(BMTCollage) {

msgPn0.etTemplateFile.text = params['TemplateFile'];
msgPn2.etInputFolder.text = params['InputFolder'];
msgPn3.etDestination.text = params['OutputFolder'];

// Collage
// checking for valid settings
buttonPanel.runBtn.onClick = function() {

// check if the template setting is proper
var tmpltfld = BMTCollage.msgPn0.etTemplateFile.text;
if (tmpltfld.length == 0) {
alert(strAlertSpecifyTemplateFile);
return;
}
var testFile = new File(tmpltfld);
if (!testFile.exists) {
alert(strAlertTemplateFileNotExist);
return;
}

var inptfld = BMTCollage.msgPn2.etInputFolder.text;
if (inptfld.length == 0) {
alert(strAlertSpecifyInputFolder);
return;
}
var testFolder = new Folder(inptfld);
if (!testFolder.exists) {
alert(strAlertInputFolderNotExist);
return;
}

// check if the output folder setting is proper
var destination = BMTCollage.msgPn3.etDestination.text;
if (destination.length == 0) {
alert(strAlertSpecifyDestination);
return;
}
var testFolder = new Folder(destination);
if (!testFolder.exists) {
alert(strAlertDestinationNotExist);
return;
}

// See if the input folder and the output folder are the same
if (BMTCollage.msgPn3.etDestination.text == BMTCollage.msgPn2.etInputFolder.text) {
var result = confirm("Are you sure you want your output folder to be the same as your input folder");
if (result) {
} else {
return;
}
}

close( 1 ); // Close dialog window and process
}

buttonPanel.helpBtn.onClick = function() {help();}

buttonPanel.cancelBtn.onClick = function() {close( 2 );}
}
} // end createDialog

function runDialog(BMTCollage){
// Warn the user if they have an open document and exit the script with return
//if (documents.length > 0){
// alert ("This script requires that there are no open documents to run.");
//return;
//}
BMTCollage.onShow = function() {
var ww = BMTCollage.bounds.width;
var hh = BMTCollage.bounds.height;
BMTCollage.bounds.x = 78;
BMTCollage.bounds.y = 100;
BMTCollage.bounds.width = ww;
BMTCollage.bounds.height = hh;
}
return BMTCollage.show()
}

//=====================Start=====================================================

var BMTCollage = createDialog()
initializeDialog(BMTCollage)

if (runDialog(BMTCollage) == 1){
// transfer values from the dialog to my internal params
params['TemplateFile'] = BMTCollage.msgPn0.etTemplateFile.text;
params['InputFolder'] = BMTCollage.msgPn2.etInputFolder.text;
params['OutputFolder'] = BMTCollage.msgPn3.etDestination.text;
// Save the params from the above
SaveParamsToDisk( GetDefaultParamsFile(), params );

// Gets the template file from the UI
var templateFile = BMTCollage.msgPn0.etTemplateFile.text;
var templateFile = new Folder(templateFile);
//alert(templateFile);

// Gets the input folder from the UI
var inputFolder = BMTCollage.msgPn2.etInputFolder.text;
//alert(inputFolder);
var inputFolder = new Folder(inputFolder);

// Gets the output folder from the UI
var outputFolder = BMTCollage.msgPn3.etDestination.text;
//alert(outputFolder);
var outputFolder = new Folder(outputFolder);

//alert('Template="' + templateFile + '"\nImages from "' + inputFolder + '"\nSaved to "' + outputFolder +'"');

startDate = (getDateTime());
var time1 = Number(timeString());
var mockupFile = new Array();
mockupFile = templateFile.getFiles(/\.(psd|psb)$/i);
if (!mockupFile.length) {alert("there are no Mockup Templates in folder\n\n" + templateFile + "/" ); }
else{
var runMain = true; // if mash hast a terminating error
for (var m = 0; m < mockupFile.length; m++) {
if (runMain) {
open(File(mockupFile[m]));
app.activeDocument.suspendHistory('BatchUpdateSmartObject','main()');
activeDocument.close(SaveOptions.DONOTSAVECHANGES); // Close No Save
}
}
if (countSame & runMain) {
if (replaceCount) {
var time2 = Number(timeString());
endDate = (getDateTime());
alert(startDate + " Start\n"
+"Processed " + replaceCount + " Mockups\nFor " + mockupFile.length + " Mockup Templates\n"
+((time2-time1)/60000 ).toPrecision(5)+" Minutes\n" + endDate + " End"
);
}
else alert("No files found");
}
}
} // end if (runDialog(BMTCollage) == 1)

// Return the app preferences
app.preferences.rulerUnits = startRulerUnits;
app.preferences.typeUnits = startTypeUnits;
app.displayDialogs = saveDialogMode;

//////////////////////////////////////////////////////////////////////////////////
// The end //
//////////////////////////////////////////////////////////////////////////////////
function main(){
var templateName = activeDocument.name.replace(/\.[^\.]+$/, '');
try {
var myDocument = app.activeDocument;
try { var theName = myDocument.name.match(/(.*)\.[^\.]+$/)[1]; } catch(e) { alert(e); }
var layers = myDocument.layers;
var theLayer = layers[0];
if (theLayer.kind != "LayerKind.SMARTOBJECT") { alert(" Top layer is not a smart object") }
else {
// add support for more tha one smart object layer
//Count top smart obj
var objCount = 0;
i=0
var theLayers = new Array();
while ( layers[i].kind == "LayerKind.SMARTOBJECT" ) { theLayers.push(layers[i]);objCount++ ; i++;}
//alert("objCount " + objCount);
// test the input folders exists
foundFolders=true; notFound = "Required Folders missing\n";
var objFolders = new Array();
for (var i = 0; i < objCount; i++) {
objFolders.push(new Folder(inputFolder + "/obj" + i));
if (!objFolders[i].exists) {
notFound = notFound + objFolders[i] + "\n";
foundFolders=false;
}
}
if (!foundFolders) {alert(notFound); runMain = false;}
else {
var rplFiles = new Array();
if (!BMTCollage.msgPnl.EditImage.st.value) for (var i = 0; i < objCount; i++) { rplFiles[i] = objFolders[i].getFiles(/\.(psd|tif|jpg|png)$/i); } // gets file list
else for (var i = 0; i < objCount; i++) { rplFiles[i] = objFolders[i].getFiles(/\.(nef|cr2|crw|dcs|raf|arw|orf|dng|psd|tif|jpg|png)$/i); } // gets file list
replaceCount=rplFiles[0].length;
//alert(replaceCount)
countSame=true;
for (var i = 0; i < objCount; i++) { if (rplFiles[i].length!=replaceCount) countSame=false;} // test all flist are the same lengt

if (countSame){
for (var r = 0; r < replaceCount; r++) { // or replacement count
for (var o = 0; o < objCount; o++) { // for objCount
//The Layer and the file
if (BMTCollage.msgPnl.EditImage.st.value) {
if (objectIsPsObject(theLayers[o])) theLayer = editContents(rplFiles[o][r], theLayers[o], BMTCollage.msgPnl.RotateForFit.st.value, BMTCollage.msgPnl.FitImage.st.value);
else {
alert (theLayers[o] + " Object is not safe to edit");
return;
}
}
else theLayer = replaceContents(rplFiles[o][r], theLayers[o]);
}
var theNewName = rplFiles[0][r].name.match(/(.*)\.[^\.]+$/)[1];
outputFile = outputFolder + "/" + theNewName +" " + templateName ; // Construct full output file path
SaveAsJPEG( outputFile , 10 );
if (BMTCollage.msgPnl.SavePSDfile.st.value) SaveAsPSD( outputFile, true );
}
}
else {alert("Replacemen object counts are not the same " + replaceCount); runMain = false;}
}
}
}
catch(e) { alert(e); }
return;
}
//////////////////////////////////////////////////////////////////////////////////
// Helper Functions //
//////////////////////////////////////////////////////////////////////////////////

function replaceContents(newFile, theSO)
{
try {
var lyrVis = theSO.visible;
app.activeDocument.activeLayer = theSO;
var idplacedLayerReplaceContents = stringIDToTypeID("placedLayerReplaceContents");
var desc3 = new ActionDescriptor();
var idnull = charIDToTypeID("null");
desc3.putPath(idnull, new File(newFile));
var idPgNm = charIDToTypeID("PgNm");
desc3.putInteger(idPgNm, 1);
executeAction(idplacedLayerReplaceContents, desc3, DialogModes.NO);
theSO.visible = lyrVis;
return app.activeDocument.activeLayer
}
catch(e) { alert(e); }
}

function objectIsPsObject(SOlayer) {
//Thanks to r-bin
var ext = smartobject_file_ext(SOlayer);
var rc = true;
switch (ext)
{
case "nef":
case "cr2":
case "crw":
case "raf":
case "orf":
case "mrw":
case "dcr":
case "mos":
case "raw":
case "pef":
case "srf":
case "dng":
case "x3f":
case "erf":
case "sr2":
case "kdc":
case "mfw":
case "mef":
case "arw":
case "nrw":
case "rw2":
case "rwl":
case "iiq":
case "3fr":
case "fff":
case "srw":
case "ai":
case "svg":
case "pdf":
case "esp":
rc = false.
break;
case "error":
rc = false;
break;
default:
rc = true;
break;
}
return rc;
}

function smartobject_file_ext(layer) {
try {
var r = new ActionReference();
r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("smartObject"));
r.putIdentifier(stringIDToTypeID("layer"), layer.id);
var name = executeActionGet(r).getObjectValue(stringIDToTypeID("smartObject")).getString(stringIDToTypeID("fileReference"));

var n = name.lastIndexOf(".");
if (n < 0) return "";

return name.substr(n+1).toLowerCase();
}
catch (e) { return "error"; }
}

function editContents(newFile, theSO, rotateForBestFit, fitImage) {
try {
var lyrVis = theSO.visible;
app.activeDocument.activeLayer = theSO;
var smartObject = openSmartObject (theSO); // open smart object;
smartObject.flatten();
smartObject.activeLayer.isBackgroundLayer=0; // Make it a normal Layer
smartObject.selection.selectAll();
smartObject.selection.clear(); // Clear
var objWidth=smartObject.width.value;
var objHeight=smartObject.height.value;
open(File(newFile)); // open into a document
var layers = activeDocument.layers;
activeDocument.activeLayer = layers[layers.length-1]; // Target Bottom Layer
activeDocument.activeLayer.isBackgroundLayer=0; // Make it a normal Layer
try {
var objFile= app.activeDocument; // image document
if (rotateForBestFit) {
if (objFile.width.value<objFile.height.value&&objWidth>objHeight ) { objFile.rotateCanvas(-90.0); } // Rotate portraits
if (objFile.height.value<objFile.width.value&&objHeight>objWidth ) { objFile.rotateCanvas(-90.0); } // Rotate landscapes
}
if (!fitImage) {
if (objFile.width.value/objFile.height.value > objWidth/objHeight) { objFile.resizeImage(null, objHeight, null, ResampleMethod.BICUBIC); } // wider
else {objFile.resizeImage(objWidth, null, null, ResampleMethod.BICUBIC);} // same aspect ratio or taller
}
else{
if (objFile.width.value/objFile.height.value > objWidth/objHeight) {objFile.resizeImage(objWidth, null, null, ResampleMethod.BICUBIC); } // wider
else {objFile.resizeImage(null, objHeight, null, ResampleMethod.BICUBIC);}
}
try {objFile.resizeCanvas(objWidth, objHeight, AnchorPosition.MIDDLECENTER);}
catch(e){}
try{
mrkLayer = objFile.artLayers.add(); // Add a Layer
mrkLayer.name = "TL BR Stamp"; // Name Layer
mrkLayer.blendMode = BlendMode.OVERLAY; // blend mode
}
catch(e){}
mrkColor = new SolidColor;
mrkColor.rgb.red = 128;
mrkColor.rgb.green = 128;
mrkColor.rgb.blue = 128;
try{
var selectedRegion = Array(Array(0,0), Array(1,0), Array(1,1), Array(0,1)); // Top Right
objFile.selection.select(selectedRegion);
objFile.selection.fill(mrkColor);
var selectedRegion = Array(Array(objWidth-1,objHeight-1), Array(objWidth,objHeight-1), Array(objWidth,objHeight), Array(objWidth-1,objHeight)); // Bottom Right
objFile.selection.select(selectedRegion);
objFile.selection.fill(mrkColor);
}
catch(e){}
objFile.selection.selectAll();
try {objFile.selection.copy(true); } //copy merge resized image into clipboard
catch(e){objFile.selection.copy(); } //copy resized image into clipboard
objFile.close(SaveOptions.DONOTSAVECHANGES); //close image without saving changes
smartObject.paste(); //paste change smart object content from being empty
}
catch(e) { objFile.close(SaveOptions.DONOTSAVECHANGES); } // close image without saving changes smart object is empty though
if (smartObject.name.indexOf(".jpg")!=-1) smartObject.flatten();
smartObject.close(SaveOptions.SAVECHANGES); //close and save
theSO.visible = lyrVis;
return app.activeDocument.activeLayer
}
catch(e) { alert(e); }
}

////// open smart object //////
function openSmartObject (theLayer) {
if (theLayer.kind == "LayerKind.SMARTOBJECT") {
// =======================================================
var idplacedLayerEditContents = stringIDToTypeID( "placedLayerEditContents" );
var desc2 = new ActionDescriptor();
executeAction( idplacedLayerEditContents, desc2, DialogModes.NO );
};
return app.activeDocument
};

function SaveAsJPEG(saveFile, jpegQuality){
var doc = activeDocument;
if (doc.bitsPerChannel != BitsPerChannelType.EIGHT) doc.bitsPerChannel = BitsPerChannelType.EIGHT;
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.embedColorProfile = true;
jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
jpgSaveOptions.matte = MatteType.NONE;
jpgSaveOptions.quality = jpegQuality;
activeDocument.saveAs(File(saveFile+".jpg"), jpgSaveOptions, true,Extension.LOWERCASE);
}

function SaveAsPSD( inFileName, inEmbedICC ) {
var psdSaveOptions = new PhotoshopSaveOptions();
psdSaveOptions.embedColorProfile = inEmbedICC;
app.activeDocument.saveAs( File( inFileName + ".psd" ), psdSaveOptions );
}

function help() {
try{
var URL = new File(Folder.temp + "/PhotoCollageToolkit.html");
URL.open("w");
URL.writeln('<html><HEAD><meta HTTP-EQUIV="REFRESH" content="0; url=http://www.mouseprints.net/old/dpr/PhotoCollageToolkit.html"></HEAD></HTML>');
URL.close();
URL.execute();
}catch(e){
alert("Error, Can Not Open.");
};
}

///////////////////////////////////////////////////////////////////////////////
// Function: initExportInfo
// Usage: create our default parameters
// Input: a new Object
// Return: a new object with params set to default
///////////////////////////////////////////////////////////////////////////////
function initExportInfo(exportInfo) {
exportInfo.destination = new String("");
exportInfo.fileNamePrefix = new String("untitled_");
exportInfo.visibleOnly = false;
// exportInfo.fileType = psdIndex;
exportInfo.icc = true;
exportInfo.jpegQuality = 8;
exportInfo.psdMaxComp = true;
exportInfo.tiffCompression = TIFFEncoding.NONE;
exportInfo.tiffJpegQuality = 8;
exportInfo.pdfEncoding = PDFEncoding.JPEG;
exportInfo.pdfJpegQuality = 8;
exportInfo.targaDepth = TargaBitsPerPixels.TWENTYFOUR;
exportInfo.bmpDepth = BMPDepthType.TWENTYFOUR;

try {
exportInfo.destination = Folder(app.activeDocument.fullName.parent).fsName; // destination folder
var tmp = app.activeDocument.fullName.name;
exportInfo.fileNamePrefix = decodeURI(tmp.substring(0, tmp.indexOf("."))); // filename body part
} catch(someError) {
exportInfo.destination = new String("");
// exportInfo.fileNamePrefix = app.activeDocument.name; // filename body part
}
}

// Find the location where this script resides
function findScript() {
var where = "";
try {
FORCEERROR = FORCERRROR;
}
catch(err) {
// alert(err.fileName);
// alert(File(err.fileName).exists);
where = File(err.fileName);
}
return where;
}

function timeString () {
var now = new Date();
return now.getTime()
};

// Function for returning current date and time
function getDateTime() {
var date = new Date();
var dateTime = "";
if ((date.getMonth() + 1) < 10) {
dateTime += "0" + (date.getMonth() + 1) + "/";
} else {
dateTime += (date.getMonth() + 1) + "/";
}
if (date.getDate() < 10) {
dateTime += "0" + date.getDate() + "/";
} else {
dateTime += date.getDate() + "/";
}
dateTime += date.getFullYear() + ", ";
if (date.getHours() < 10) {
dateTime += "0" + date.getHours() + ":";
} else {
dateTime += date.getHours() + ":";
}
if (date.getMinutes() < 10) {
dateTime += "0" + date.getMinutes() + ":";
} else {
dateTime += date.getMinutes() + ":";
}
if (date.getSeconds() < 10) {
dateTime += "0" + date.getSeconds();
} else {
dateTime += date.getSeconds();
}
return dateTime;
}

// resetPrefs function for resetting the preferences
function resetPrefs() {
preferences.rulerUnits = startRulerUnits;
preferences.typeUnits = startTypeUnits;
displayDialogs = startDisplayDialogs;
}

// CheckVersion
function CheckVersion() {
var numberArray = version.split(".");
if ( numberArray[0] < 9 ) {
alert( "You must use Photoshop CS2 or later to run this script!" );
throw( "You must use Photoshop CS2 or later to run this script!" );
}
}

// load my params from the xml file on disk if it exists
// gParams["myoptionname"] = myoptionvalue
// I wrote a very simple xml parser, I'm sure it needs work
function LoadParamsFromDisk ( loadFile, params ) {
// var params = new Array();
if ( loadFile.exists ) {
loadFile.open( "r" );
var projectSpace = ReadHeader( loadFile );
if ( projectSpace == GetScriptNameForXML() ) {
while ( ! loadFile.eof ) {
var starter = ReadHeader( loadFile );
var data = ReadData( loadFile );
var ender = ReadHeader( loadFile );
if ( ( "/" + starter ) == ender ) {
params[starter] = data;
}
// force boolean values to boolean types
if ( data == "true" || data == "false" ) {
params[starter] = data == "true";
}
}
}
loadFile.close();
if ( params["version"] != gVersion ) {
// do something here to fix version conflicts
// this should do it
params["version"] = gVersion;
}
}
return params;
}

// save out my params, this is much easier
function SaveParamsToDisk ( saveFile, params ) {
saveFile.encoding = "UTF8";
saveFile.open( "w", "TEXT", "????" );
// unicode signature, this is UTF16 but will convert to UTF8 "EF BB BF"
saveFile.write("\uFEFF");
var scriptNameForXML = GetScriptNameForXML();
saveFile.writeln( "<" + scriptNameForXML + ">" );
for ( var p in params ) {
saveFile.writeln( "\t<" + p + ">" + params[p] + "</" + p + ">" );
}
saveFile.writeln( "</" + scriptNameForXML + ">" );
saveFile.close();
}

// you can't save certain characters in xml, strip them here
// this list is not complete
function GetScriptNameForXML () {
var scriptNameForXML = new String( gScriptName );
var charsToStrip = Array( " ", "'", "." );
for (var a = 0; a < charsToStrip.length; a++ ) {
var nameArray = scriptNameForXML.split( charsToStrip[a] );
scriptNameForXML = "";
for ( var b = 0; b < nameArray.length; b++ ) {
scriptNameForXML += nameArray[b];
}
}
return scriptNameForXML;
}

// figure out what I call my params file
function GetDefaultParamsFile() {
//var paramsFolder = new Folder( path + "/Presets/" + gScriptName );
//var paramsFolder = new Folder( Folder.temp + "/JJMack's Scripts/" + gScriptName );
var paramsFolder = new Folder( "~/Application Data/JJMack's Scripts/" + gScriptName );
//alert("paramsFolder = " + paramsFolder );
paramsFolder.create();
return ( new File( paramsFolder + "/" + gScriptName + ".xml" ) );
}

// a very crude xml parser, this reads the "Tag" of the <Tag>Data</Tag>
function ReadHeader( inFile ) {
var returnValue = "";
if ( ! inFile.eof ) {
var c = "";
while ( c != "<" && ! inFile.eof ) {
c = inFile.read( 1 );
}
while ( c != ">" && ! inFile.eof ) {
c = inFile.read( 1 );
if ( c != ">" ) {
returnValue += c;
}
}
} else {
returnValue = "end of file";
}
return returnValue;
}

// very crude xml parser, this reads the "Data" of the <Tag>Data</Tag>
function ReadData( inFile ) {
var returnValue = "";
if ( ! inFile.eof ) {
var c = "";
while ( c != "<" && ! inFile.eof ) {
c = inFile.read( 1 );
if ( c != "<" ) {
returnValue += c;
}
}
inFile.seek( -1, 1 );
}
return returnValue;
}

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
May 27, 2020 May 27, 2020

Copy link to clipboard

Copied

Jpeg file format does not support transparency.  You can use that script option to save a populated PSD file in addition to the outputted jpeg file.  If the PSD file format does not meat your requirements. You can use Image Processor Pro to batch save PNG files for  the populated PSD files. Or you can modify the Script to save PNG File instead of Jpeg files.  IMO Jpeg are better for printing. PNG is a web image file. If your Smart Object Replacement images are PNG Files with transparent backgrounds.  You you may be better off also using the Script Edit  option to have the script edit the PNG replacements into the object.  The Scripts default operation is to use replace content.    Replace content will trim  png image transparent borders you may find the replace content operation is not what you want.   My Edit object process tries the preserve transparent boarders.  However if the replacement image's aspect ratio is not the same as the smart object some trimming will happen.

JJMack

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Participant ,
Oct 20, 2023 Oct 20, 2023

Copy link to clipboard

Copied

LATEST

So there are 2 main ways to automate this process: 1) Using a Photoshop plugin, 2) Using a Photoshop script.

 

With the plugin approach, you can use the Batch Replace Smart Objects plugin to do exactly what the name suggests -- batch replace the Smart Object in your Photoshop mockup template with all images from your input folder (then export each updated mockup image to an output folder.) If you need to do this for several mockup templates in a row (for example, if you're creating 5 or 10 different product photos for each of your new T-shirt artwork designs), you can also use this plugin to do that by creating and saving a Workflow, with each step in the workflow corresponding to each of the mockup templates you want to use. Then just run the workflow, and it'll automate the process of creating all the different mockup images for all of your different artwork designs. Pretty straightforward.

 

With the scripting approach, you'll have to write a .jsx script that automates this process. You could probably find some scripts on these forums that are similar to what you're going for, then just customize them in a few spots, as needed, for your specific mockup-creation workflow. Modify a few filepaths/folderpaths obviously, maybe change how the filenames are saved, update the JPEG quality settings based on your image compression needs, then if needed wrap it all in a function if you have a multi-step operation you need to run -- so you can just pass your parameters into the function instead of needing to repeat the same codeblock several times, or instead of needing to manually run slightly different versions of the script multiple times over. Lots of these scripts require you to physically be there at your computer each time to manually select the folderpaths/documents for each operation, but there's no reason you can't just hardcode that into the script if your workflow is standardized.

 

If you go the scripting route, I would HIGHLY recommmend that you make a few modifications to your scripts + the way you use them: 1) I'd set up a "purge all caches" operation, for each loop iteration, to prevent your RAM usage from climbing up and up as the automated operation runs; 2) Set your History States to 0 or 1 before you run sort of .jsx scripted operation which automates this. (Then remember to revert it back to your preferred setting afterwards -- otherwise Ctrl + Z / Undo operations will be useless in Photoshop.) In my case at least, these changes were VITAL for ensuring that my Photoshop RAM usage didn't skyrocket + crash Photoshop/my computer, when running large batch sizes. Shouldn't be an issue if you're doing very small batches, but if you're automating the creation of lots of images, I'd make sure to do both of those.

 

(Note that I haven't had to do either of these using that Photoshop plugin and haven't noticed any performance / RAM usage issues -- I believe because plugins are written in UXP, which is just a different way of executing commands programmatically in Photoshop, and I think the UXP approach is just more modern + more supported by Adobe than .jsx scripting. Don't quote me on that, though.)

 

Regardless of which approach you use, I would recommend that you reduce the size of your Photoshop mockup template down to the aspect ratio of the actual final images you'll be using on your website / in your workflow. Many mockup templates come in gigantic original sizes, that are just WAY larger than you need. You can dramatically speed up the automation process by just resizing the Photoshop document to the actual aspect ratio that's needed. It obviously takes significantly longer to perform operations, and save images, if the Photoshop documents you're using are enormous in size. So shrink it down to what's needed, + have the automated process run way faster -- which translates into, more throughput, higher volume, and the ability to create way more images per unit time.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines