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

ExtendScript Photoshop Edit Contents Smart Layer

New Here ,
Oct 31, 2019 Oct 31, 2019

Copy link to clipboard

Copied

I have a psd file with an embedded psd file. Using photoshop normally, I double on the layer icon to edit the contents (or choose "edit contents" from the dropdown). I can not seem to find out how to open/edit it with extendscript/javascript. It is a legend that we use on our plans and would like to add content via scripting but need to find out how to edit the contents first. Note: this is not a linked file externally, it is embedded.

Thanks in advance.

TOPICS
Actions and scripting

Views

12.1K

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

correct answers 1 Correct answer

Community Expert , Oct 31, 2019 Oct 31, 2019

One way:

 

app.runMenuItem(stringIDToTypeID('placedLayerEditContents'));

 

https://community.adobe.com/t5/Photoshop/Script-to-Export-Contents-of-all-Smart-Objects-in-a-Photoshop/m-p/10644877

Votes

Translate

Translate
Adobe
Community Expert ,
Oct 31, 2019 Oct 31, 2019

Copy link to clipboard

Copied

One way:

 

app.runMenuItem(stringIDToTypeID('placedLayerEditContents'));

 

https://community.adobe.com/t5/Photoshop/Script-to-Export-Contents-of-all-Smart-Objects-in-a-Photosh...

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
New Here ,
Nov 01, 2019 Nov 01, 2019

Copy link to clipboard

Copied

Thanks Stephen & JJmack, answer was right in front of me in the code but couldn't see it through the forest.

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 ,
Oct 31, 2019 Oct 31, 2019

Copy link to clipboard

Copied

A PSD Object will open in Photoshop and your script will still be in cintrol of Photoshop and can edit the opened object. However, you need to be careful opening Smart Object Layers contents using A Photoshop script.  There are many ways smart object layers are created. All smart Object Layers's Object are not Photoshop Objects.  If you open them in a Photoshop script they will open in other applications or a Photoshop ACR Plug-in. The Photoshop script that opened the object  will lose control till the Application or pug-in execution finishes The script can not edit such objects.   R-bin posted code you can use to test the type object a smart object contains.  To determine if the object will open in Photoshop or not. I use that code in my Batch Photoshop Mockups scripts when the user want toe edit object rather than replace smart object layer object using replace content.   My scripts can not handle editing Mockup templates smart object layers that have none Photoshop object. Only replace content is supported  for none when Smart Object layer have none Photoshop Objects.

 

 

 

 


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;
}

 

 

 

 r-bin code 

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
Community Expert ,
Oct 31, 2019 Oct 31, 2019

Copy link to clipboard

Copied

JJMack, the code as posted does not work...

 

When I add:

 

objectIsPsObject();

 

An error is returned from your posted code:

 

Runtime Error: Error Code# 24: smartobject_file_ext is not a function on the following code entry:
 
var ext = smartobject_file_ext(SOlayer);

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 ,
Oct 31, 2019 Oct 31, 2019

Copy link to clipboard

Copied

Correct you need to pass a smart object layer object to the function. You did not pass a smart object layer. If you pass a smart object layer the  function will return true if the layer object work file extension will open in photoshop or false if the object will not open in Photoshop. 

 

function objectIsPsObject(SOlayer) {

...

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
Community Expert ,
Oct 31, 2019 Oct 31, 2019

Copy link to clipboard

Copied

Thanks, as I mostly hack at scripting, this is not immediately "plug-n-play" and I'll have to play a bit to try to make this work without a working sample.

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 ,
Nov 01, 2019 Nov 01, 2019

Copy link to clipboard

Copied

Working sample Batch Mockup Scripts of its use it is plug and play as posted I use copy paste to post it.

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
Community Expert ,
Nov 02, 2019 Nov 02, 2019

Copy link to clipboard

Copied

Thanks JJ, I have kicked this around without success. This is due to my current knowledge level (or lack thereof), not your code.

 

With a (psb) smart object layer active, the single line of code that I previously posted opens the smart object layer.

 

I have not had the same successful result using the code from r-bin. I even tried adding PSD and PSB into the list of extensions, however that is probably not the issue.

 

By "plug n play" I meant that the code should be complete and concise to do exactly what is required without any further editing.

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 ,
Nov 02, 2019 Nov 02, 2019

Copy link to clipboard

Copied

The function is complete.   A function is not a complete script. And your one line has problems it will work only if the active layer is a smart object layer and the object is supported by photoshop.  It will fail in all other cases. Here no active layer and also with an  active layer that is a smar object layer with an object that photoshop does not support. In the case vector smart object. That object opened in Chrome on my machine. It an SVG file create by Adobe AI.

Capture.jpg

 

 

The code does not open open a smart object layer's object.  The code test a smart object layer to see if you use open smart object layer object to open the object into Photoshop.   If you pass your smart object layer that has a PSB object it would return true you can.   Your line of code  edits Photoshop active document active layers smart object. 

 

 

 

 

app.runMenuItem(stringIDToTypeID('placedLayerEditContents'));

 

 

 

 

There are problems with that if not user properly. If the active layers is not a smart object layers the lines will through a script error. If the active layers is a smart object layers and the object is not a Photoshop supported object it will not fail. However, the script will lose control  and not be able to edit the object for it will not open in Photoshop. An other Application like AI or a Plug-In like ACR will be what open the object not Photoshop. If you know active layer is a smart object layer and the layer's object is a Photoshop object your code will work.  I your not sure of what kind of object the smart object is you need r-bin code or your script will fail its Murphy's law.

Your one line should be a if statement. With or without the else.

 

 

 

 

if (objectIsPsObject(activeDocument.activeLayer)) app.runMenuItem(stringIDToTypeID('placedLayerEditContents'));
else alert(activeDocument.activeLayer.name + " Object can not be edited using Photoshop its unchanged.");

 

 

 

I do not know JavaScript or Photoshop Scripting. I do have a programming background so I hack  at code.  You are learning you need to read more code to get a better understanding of what is what. It should not be hard for you read that function to see all it does is return True or False. 

 

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
Community Expert ,
Nov 02, 2019 Nov 02, 2019

Copy link to clipboard

Copied

We all make mistakes and I did forget to paste the inner function smartobject_file_ext. So you were right when you posted the code I posted does not work.  So here is a  script your one line script to open Photoshop active layers smart object layer object in  Photoshop for editing. The code to edit the object is not included. However. That code should end with a Close that Saves the edits. So the opened work file will  closed out of Photoshop so the active document will become the original current document  Its Active Smart object layer's  object will be updated and new pixels rendered for the layers content.  As the Script stands there will be at least two open documents in Photoshop when it ends. The original document you ran the script from and the opened temp work document. Should] the object be a Photoshop object.

 

 

if (!documents.length) alert('There are no documents open.', 'No Document');
else {
   if (app.activeDocument.activeLayer.kind!=LayerKind.SMARTOBJECT) alert("ActiveLayer not Smart Object Layer");
   else {
      if (!objectIsPsObject(activeDocument.activeLayer)) alert(activeDocument.activeLayer.name + " Object can not be edited using Photoshop its unchanged.");
      else app.runMenuItem(stringIDToTypeID('placedLayerEditContents'));
      // Add code here to edit the smart object temp work file

     // Close the work file with save to clost the temp wok file out of Phtoshop and have Photoshop updater the orifinals smart object layers objeyy
   }
}

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"; }  
}   

 

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
Community Expert ,
Nov 03, 2019 Nov 03, 2019

Copy link to clipboard

Copied

Thank you JJMack, that is a really useful post, more than what I was hoping for from the start, kudos!

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 ,
Nov 03, 2019 Nov 03, 2019

Copy link to clipboard

Copied

Once opened there are still problem you need to address in the edit code smart objects file types differ and features like Place should be avoided because of the strange things the Photoshop Place feature does. You can use place if you know how place works most users do not the have it wrong as to how place works it resizes because of different resolutions and may also scale the created smart object. You need to know how to deal with Place's operation.

 

 Then you need to flatten the document if the object type is a jpeg object for you need to use a save to save the work file save as will not do that.  Save will fail if there are layers.

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
Community Expert ,
Nov 03, 2019 Nov 03, 2019

Copy link to clipboard

Copied

Here is a function I wrote that edits a Photoshop smart object layer's Object in Photoshop.  This is not a complete script it is a function used  in  my Batch Mockup Scripts that is in the package I posted. Note it uses Open Copy Paste not Place so a third document is opened.  The Document is used to resize the replacement content and which is then pasted into the  smart object temp work document.  That Document is closed and the temp work document is closed with save and close.  Photoshop then updates the smart object layer in the document that was active when the script function was used. With my Batch Mockup scripts that document would be a Mockup template that script opened to be batch populated. The function is pass the replacement file, the smart object layer the has a Photoshop object, and two edit options Boolean, rotate for best fit and fit image. The function open both the Object and the replacement content file. Note all the Try Catch statement I needed to use to gets the function to work well. I needed 6 of them. The function may run into a Photoshop problem and raise an alert message and when  the message is dismissed the script will continue to process the batch without updating that layers smart object layer. So far I have not see this happen. If it does there is a possibility of documents opened in the function  being left open in Photoshop. It not always easy to program around software and file problems .

 

 

 

 

 

 

 

 

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); }    
}     	

 

 

 

 

 

 

The inner function to open the object function uses Action manager code  not your run menu item DOM code. In my Scripts this should work for the object has been tested to be a Photshop supported object. If the function fails to open the object the try catch in edit content function will catch this. So far this has not happened.  If it does happen that smart object layers object will not be updated and the usere will see the alert message that a error happened with the layers object. The function returns the open work document when open object works.

 

 

 

 

 

 

////// 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
};

 

 

 

 

 

 

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
Advocate ,
Jan 01, 2021 Jan 01, 2021

Copy link to clipboard

Copied

@JJMack Hi there,

 

ive used part of a different script and altered it. It has the same idea, which is to open an smarotbject plane a new image save the temp file, close and export a JPG. I had it working at a certain point, but stuppidly i didnt make a backup copy of that one. I kept optimizing it but suddenly it would run properly. I keeps placing the image in the main document. The issue is that Photoshops GUI doesnt seem to update properly before the placement code is run. I tried adding sleep, app.refresh and wait commands, but non of them help. I also tried part of you edit object code but it returns an error. Somehow the code runs before the smartobject is opened. On OSX it did run nice at one point, that was CC2018 at home i run a newer version, 2021, but i find that version kind of slaggish. The GUI isnt responding very smooth on Windows. For instance when i have 2 docs open and close one, its litteraly takes seconds before the GUI updates and show the layers of the other document. I think this GUI delay is also causing this script to fail

 

here's my test version, its a but sloppy with all those commented parts, i like to switch functions while im testing so i keep them in. When it runs i always clean it up.

 

I only get it to work when i add an alert function after the edit placed content. It seems only then does the GUI update properly. I think i could add a function which stores the main files name and path then close it and open the smartobject, but it will lose the link then i guess.

 

Do you have an idea perhaps?

// Save JPOG from placed smartbojects
// https://community.adobe.com/t5/photoshop/smart-object-automation-script/td-p/8877231?page=1

#target photoshop

// Get OS
// fromt "_LastLogEntry.jsx"
isWindows = function() {
  return $.os.match(/windows/i);
};
isMac = function() {
  return !isWindows();
};
var osPath = (isMac() ? '/' : "/"); // resolve windows vs osx paths
// alert(isMac())

function exportMockupDesigns (){
    if (app.documents.length > 0) {
        var docRef = app.activeDocument;
        var docName = docRef.name.match(/(.*)\.[^\.]+$/)[1];
        var docPath = docRef.path;
        var actLayer = docRef.activeLayer;
        // jpg options;
        var jpgopts = new JPEGSaveOptions();
        jpgopts.embedProfile = true;
        jpgopts.formatOptions = FormatOptions.STANDARDBASELINE;
        jpgopts.matte = MatteType.NONE;
        jpgopts.quality = 8;
        // check if layer is smart object;
        if (actLayer.kind != "LayerKind.SMARTOBJECT") {
            alert("selected layer is not a smart object")
        } else {
            // select files;
            if ($.os.search(/windows/i) != -1) {
                var theFiles = File.openDialog("please select files", "*.psd;*.tif;*.jpg;*.jpeg;", true)
            } else {
                var theFiles = File.openDialog("please select files", getFiles, true)
            };
            if (theFiles) {
                 var destinationFolder = Folder.selectDialog("Please select a destination folder");
                // work through the array;
                for (var m = 0; m < theFiles.length; m++) {
                    // var edit = editSmOB();
                    var edit = openSmartObject (actLayer)
                    //alert(edit)
                    if(edit) {
                        var place = placeImage(theFiles[m])
                        //alert(place)
                        saveTmpDoc()
                    }
                    if(place){
                        var theNewName = theFiles[m].name.match(/(.*)\.[^\.]+$/)[1];
                        // alert(theNewName)
                        //save jpg;
                        docRef.saveAs((new File(destinationFolder.toString() + "/" + docName + "_" + theNewName + ".jpg")), jpgopts, true);

                    }
                    // var theNewName = theFiles[m].name.match(/(.*)\.[^\.]+$/)[1];
                    //save jpg;
                    // docRef.saveAs((new File(docPath + "/" + docName + "_" + theNewName + ".jpg")), jpgopts, true);

                }
            }
        }
    }

    


    ////// get psds, tifs and jpgs from files //////
    function getFiles(theFile) {
        if (theFile.name.match(/\.(psd|tif|png|jpg|jpeg)$/i) != null || theFile.constructor.name == "Folder") {
            return true
        };
    };
    


    function cTID(s) { return app.charIDToTypeID(s); };
    function sTID(s) { return app.stringIDToTypeID(s); };


    function waitMoment(){
        var eventWait = charIDToTypeID("Wait")        
        var enumRedrawComplete = charIDToTypeID("RdCm")
        var typeState = charIDToTypeID("Stte")
        var keyState = charIDToTypeID("Stte")
        var desc = new ActionDescriptor()
        desc.putEnumerated(keyState, typeState, enumRedrawComplete)
        executeAction(eventWait, desc, DialogModes.NO)
    }

    function editSmOB() {
        app.runMenuItem(stringIDToTypeID('placedLayerEditContents'));
        waitMoment();
        return true            
        // var desc110 = new ActionDescriptor();
        // executeAction( sTID('placedLayerEditContents'), desc110, DialogModes.NO );
        // waitMoment()
        
    }

    function openSmartObject (theLayer) {
        current = app.activeDocument;
        if (theLayer.kind == "LayerKind.SMARTOBJECT") {
            runMenuItem(stringIDToTypeID('placedLayerEditContents'));
            waitMoment();
            // if ( current == app.activeDocument) {
            //     try {         
            //         var r = new ActionReference();     
            //         r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("smartObject"));  
            //         r.putIdentifier(stringIDToTypeID("layer"), theLayer.id);  
            //         var name = executeActionGet(r).getObjectValue(stringIDToTypeID("smartObject")).getString(stringIDToTypeID("fileReference"));   
            //         waitMoment();      
            //         }  
            //     catch (e) { 
            //         // throw theLayer + " Smart Object Did not Open"; }  
            //         alert(theLayer + " Smart Object Did not Open");
            //          }  
            //     var workFile = new File(Folder.temp + "/" +  name);  // May work for both Windows and Mac
            //     //alert(workFile)
            //     app.open(File(workFile));
            //     // if (workFile.exists) app.open(File(workFile));
            //     // if ( current == app.activeDocument) alert( theLayer + " Smart Object Did not Open");
            // }
        }
        return app.activeDocument
    };

    // Edit smartobject
    function editSmartObject(newLinkedFile){
        var idplacedLayerEditContents = stringIDToTypeID( "placedLayerEditContents" );
        var edtSmaObj = new ActionDescriptor();
        executeAction( idplacedLayerEditContents, edtSmaObj, DialogModes.NO );
        

        var desc224 = new ActionDescriptor();
    //     desc224.putPath( cTID('In  '), new File( "/private/var/folders/l0/wnzt19xd0tvgqwmljhfq_4rc0000gn/T/TemporaryItems/Rectangle 2.psb" ) );
        desc224.putPath( cTID('In  '), new File( "C:/Users/romboutversluijs/AppData/Local/Temp/Rounded Rectangle 1.psb" ) );
        desc224.putInteger( cTID('DocI'), 587 );
        desc224.putEnumerated( sTID('saveStage'), sTID('saveStageType'), sTID('saveSucceeded') );
        executeAction( cTID('save'), desc224, DialogModes.NO );

        
    };


    //  scale to from Scale to fit > dont know resource
    //
    function rectangle(x, y, width, height) {
        return { x:x, y:y, width:width, height:height };
    }

    //  Get layerbounds
    //  https://graphicdesign.stackexchange.com/questions/21162/photoshop-action-to-determine-dimensions-of-layer
    function layerBounds(){
        // alert(activeDocument)
        var layer = activeDocument.activeLayer; //Grab the currently selected layer
        //Calculate length and width based on the rectangular bounds of the selected layer
        var width = Number(layer.bounds[2]-layer.bounds[0]); //Grab the width
        var height = Number(layer.bounds[3]-layer.bounds[1]); //Grab the height
        
        return [width, height]
    }

    //  Place image
    function placeImage(newFile) {
        // Switch document
        // var desc111 = new ActionDescriptor();
        //     var ref13 = new ActionReference();
        //     ref13.putOffset( cTID('Dcmn'), 1 );
        // desc111.putReference( cTID('null'), ref13 );
        // desc111.putInteger( cTID('DocI'), 344 );
        // executeAction( cTID('slct'), desc111, DialogModes.NO );


        // waitMoment()
        // alert(newFile)
        var desc174 = new ActionDescriptor();
        desc174.putInteger( cTID('Idnt'), 885 );
        desc174.putPath( cTID('null'), new File(newFile));
        // desc174.putPath( cTID('null'), new File( "/Volumes/_MINDFLOW/_MINDFLOW/CLIENTS/Allusion/Export/Mockups/Rombout-Mockup-01-v8/Mockuo-08-GRID-Tags-Drk.jpg" ) );
        desc174.putBoolean( cTID('Lnkd'), true );
        desc174.putEnumerated( cTID('FTcs'), cTID('QCSt'), cTID('Qcsa') );
            var desc175 = new ActionDescriptor();
            desc175.putUnitDouble( cTID('Hrzn'), cTID('#Pxl'), 0.000000 );
            desc175.putUnitDouble( cTID('Vrtc'), cTID('#Pxl'), 0.000000 );
        desc174.putObject( cTID('Ofst'), cTID('Ofst'), desc175 );
        desc174.putUnitDouble( cTID('Wdth'), cTID('#Prc'), 234.782609 );
        desc174.putUnitDouble( cTID('Hght'), cTID('#Prc'), 234.697509 );
        executeAction( cTID('Plc '), desc174, DialogModes.NO );
        
        var tmpDoc = app.activeDocument;
        // $.sleep (5000);
        
        // var tmpDoc = app.activeDocument;
        // alert(tmpDoc.name)
        // var tmpDocWidth = new UnitValue (tmpDoc.width);
        // var tmpDocHeight = new UnitValue (tmpDoc.height);

        // alert(newFile)
        // var desc174 = new ActionDescriptor();
        // desc174.putInteger( cTID('Idnt'), 885 );
        // desc174.putPath( cTID('null'), new File(newFile));
        // // desc174.putPath( cTID('null'), new File( "/Volumes/_MINDFLOW/_MINDFLOW/CLIENTS/Allusion/Export/Mockups/Rombout-Mockup-01-v8/Mockuo-08-GRID-Tags-Drk.jpg" ) );
        // desc174.putBoolean( cTID('Lnkd'), true );
        // desc174.putEnumerated( cTID('FTcs'), cTID('QCSt'), cTID('Qcsa') );
        //     var desc175 = new ActionDescriptor();
        //     desc175.putUnitDouble( cTID('Hrzn'), cTID('#Pxl'), 0.000000 );
        //     desc175.putUnitDouble( cTID('Vrtc'), cTID('#Pxl'), 0.000000 );
        // desc174.putObject( cTID('Ofst'), cTID('Ofst'), desc175 );
        // desc174.putUnitDouble( cTID('Wdth'), cTID('#Prc'), 234.782609 );
        // desc174.putUnitDouble( cTID('Hght'), cTID('#Prc'), 234.697509 );
        // executeAction( cTID('Plc '), desc174, DialogModes.NO );
        
        // var tmpDoc = app.activeDocument;
        // alert(tmpDoc.name)
        // return tmpDoc
        return true
        // transLayer(layerBounds(),tmpDocWidth,tmpDoc);
        
    };


    //  Transform layer
    //  ScriptListener
    function transLayer(layerbounds,tmpDocWidth,tmpDoc) {    
        var scale = ((Number(tmpDocWidth) / layerBounds()[0]) * 100);
        
        var trnsLayer = new ActionDescriptor();
        trnsLayer.putEnumerated( cTID('FTcs'), cTID('QCSt'), cTID('Qcsa') );
            var adLayer = new ActionDescriptor();
            adLayer.putUnitDouble( cTID('Hrzn'), cTID('#Pxl'), -0.000000 );
            adLayer.putUnitDouble( cTID('Vrtc'), cTID('#Pxl'), 0.000000 );
        trnsLayer.putObject( cTID('Ofst'), cTID('Ofst'), adLayer );
        trnsLayer.putUnitDouble( cTID('Wdth'), cTID('#Prc'), scale);
        trnsLayer.putUnitDouble( cTID('Hght'), cTID('#Prc'), scale);
        executeAction( cTID('Trnf'), trnsLayer, DialogModes.NO );
        

        // alert(saveTmpDoc(tmpDoc))
        if(saveTmpDoc(tmpDoc)){
            closeSmartOjbectDoc(); // close tempdoc
        } // save tempdoc

    };

    // Origial save code
    // function ftn15() {
    //   function cTID(s) { return app.charIDToTypeID(s); };
    //   function sTID(s) { return app.stringIDToTypeID(s); };

    //     var desc224 = new ActionDescriptor();
    //     desc224.putPath( cTID('In  '), new File( "/private/var/folders/l0/wnzt19xd0tvgqwmljhfq_4rc0000gn/T/TemporaryItems/Rectangle 2.psb" ) );
    //     desc224.putPath( cTID('In  '), new File( ""C:\Users\romboutversluijs\AppData\Local\Temp\Rounded Rectangle 2.psb"" ) );
    //     desc224.putInteger( cTID('DocI'), 587 );
    //     desc224.putEnumerated( sTID('saveStage'), sTID('saveStageType'), sTID('saveSucceeded') );
    //     executeAction( cTID('save'), desc224, DialogModes.NO );
    // };

    function saveTmpDoc() {
        // alert(tmpDoc)
        var tmpDoc = app.activeDocument
        var tmpPath = tmpDoc.path;
        var tmpSave = tmpPath + osPath + tmpDoc.name; //tmpDoc + '/' + tmpDoc.name;
        
        alert(osPath)
        alert(tmpSave)
        var saveTmp = new ActionDescriptor();
        saveTmp.putPath( cTID('In  '), new File( tmpSave ) );
        saveTmp.putInteger( cTID('DocI'), 587 );
        saveTmp.putEnumerated( sTID('saveStage'), sTID('saveStageType'), sTID('saveSucceeded') );
        executeAction( cTID('save'), saveTmp, DialogModes.NO );


        return true

    };



    // Close document smart object
    function closeSmartOjbectDoc() {
        var clsSmaObjDoc = new ActionDescriptor();
        clsSmaObjDoc.putInteger( cTID('DocI'), 587 );
        clsSmaObjDoc.putBoolean( sTID('forceNotify'), true );
        executeAction( cTID('Cls '), clsSmaObjDoc, DialogModes.NO );
        return true
    };
}

//  Suspend History
//  Better for memory, doesnt clutter history when doing a lot automation
// exportMockupDesigns.main = function() {
//     exportMockupDesigns();
// };

// app.activeDocument.suspendHistory("Script > Export Mockup Designs", 'exportMockupDesigns.main()');
exportMockupDesigns();

 

 

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 ,
Jan 01, 2021 Jan 01, 2021

Copy link to clipboard

Copied

I have no desire to look at your code. If you are  using Photoshop Place you need to understand hop Photoshop Place feature works. Its implementation is very strange, and it will scale the replacement  object if the two documents resolution are not the same and also scale the layer to fit on canvas if the object layer created scaled  to a layer that is larger than canvas. In my mockup scripts Edit object function I do not use Photoshop Place I Open replacement and  use copy and paste. So at some point the are three Document open in Photoshop. The Mockup Template, The Smart Object Work document and the Replacement image document.  After I use copy in the replacement image document I close the replacement document and paste the resize image into the Objects Work document then save and closet the the Object work Document so Photoshop will update the Templates document smart object layer. 

 

It may be that the Object work file may not be opening in your case because of how the template Smart object works.  So Place placed the replacement into your template not  your object.  I had to change  my code a few weeks ago because of that.  Someone Posted a Template that had a Smart Object that did not Open in  Photoshop when Open smart object is used on the template's smart object layer. It Also did not throw are error sof my script destroyed the template..  Using the script listener on that template I saw the Photoshop did create the temp work file but added an Open  after  the  Open smart object  smart to open the object work file.  I had to add code to text if  the  open Smart Object opened  the work file into a photoshop document and if not open  use file open to open the work file Photoshop created but failed to open.

 

The code I posted for you hads a  function that opened the smar object that I had to update to insure the work document opens. here is that code.

////// open smart object //////
function openSmartObject (theLayer) {
	current = app.activeDocument;
	if (theLayer.kind == "LayerKind.SMARTOBJECT") {
		runMenuItem(stringIDToTypeID('placedLayerEditContents'));
		if ( current == app.activeDocument) {
			try {         
				var r = new ActionReference();     
				r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("smartObject"));  
				r.putIdentifier(stringIDToTypeID("layer"), theLayer.id);  
				var name = executeActionGet(r).getObjectValue(stringIDToTypeID("smartObject")).getString(stringIDToTypeID("fileReference"));         
				}  
			catch (e) { throw theLayer + " Smart Object Did not Open"; }  
			var workFile = new File(Folder.temp + "/" +  name);  // May work for both Windows and Mac
			if (workFile.exists) app.open(File(workFile));
			if ( current == app.activeDocument) throw theLayer + " Smart Object Did not Open";
		}
	}
	return app.activeDocument
};

 

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
Advocate ,
Jan 01, 2021 Jan 01, 2021

Copy link to clipboard

Copied

Thanks, for the semi reply.

 

I know how most of it works, the issue is not related to what your explaining though. My issue is that i run an edit command and then after that it should place an image into that smartobject file. I already know the scale so i added that to the place command. Im thinking of either making a dialog for that. But i also got a function which get the bounds of the document i then get the bound of the placed file, with those two i can figure out the proper scaling i need.

 

The issue is that photoshop runs all the code before that smartobject is actually opened. I need photoshop to wait until that document is open. I feels like its running asynchronous, if i named it correct. Its running multiple actions before 1 is finished.

here's an image from a Medium article as an example and to clearify what i think is happening
example synchronous vs asynchronousexample synchronous vs asynchronous

 

My work around for now is have that smartobject open already, then i simply use a switch command and save in between. This works, i let it run a couple times and each time i got the proper exports.

 

Im just going insane of why i had it working at one point andcant seem to replicate that code. I used scriptlistener and scriptfix to get most parts i need to edit the files. Than added some extras for functionality.

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 ,
Jan 01, 2021 Jan 01, 2021

Copy link to clipboard

Copied

Two point  I just tried to a made were.

 

Place implementation is strange.  Place may well scale the smart object image.  You can not get the object size for sure using the layers bounds unless you first scale the layer to 100%. If may have been scaled to fit on canvas.  Resized to 100% may also get a size different than the actual image because resolutions did not match and the replacement image was scaled.  You can resize that scaled object 100% size to fill the object size.

 

If you feel the document did not open on time it may be it will not open.  Like the Problem I had with the smart object in the template someone posted. My script destroyed the template because it did not open. The Active Document remained the template document. The Smart Object's  Temp Work file did not open with Photoshop menu item "placeLayerEditContents" and there was no error  I had to add code to test to see if the Active document remained the template document after the "placeLayerEditContents"  command and if it was I had to  add command to actually open the temp work file created by the "placeLayerEditContents"  command that failed to open Like Photoshop did when I manually used "placeLayerEditContents"  from Photoshop UI.  That is what was added into the code I just posted.   I have only seen that problem with the Smart Object Layer in the Template some posted and said they had a problem  opening the smart object layer in a script.   I tried in vain toe create an othe smat Object Layer the would fail to open with "placeLayerEditContents" but never found the way that smart object layer was created.

 

If you are using a Mac  there may be a problem in Photoshop or mac OS where things did not interlock correctly. If  "placeLayerEditContents"  opens your smart object Photoshop should switch document completely before the next script command executes. I have only seen an interlock problem like that on windows with Photoshop CS6 when it was first released Photoshop version 13.0  

 

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
Community Expert ,
Jan 02, 2021 Jan 02, 2021

Copy link to clipboard

Copied

I took a quick look at your code and see two problems.   First I see no code that test what kind of object is in template's smart object layer.  That is a big problem.  Not all Smart Objects are Photoshop Objects.  None Photoshop Objects will not be opened by Photoshop.  For example Vector Smart Objects will open in  AI or whatever applications open Vector image files by default. Camera RAW file will open in ACR interactive UI.

 

My scripts test Smart Object Layer object type and will bypass opening smart object layers that contain none Photoshop objects.  If  template has a smart object that is not a Photoshop object the open smart object function will not open those object in Photoshop.  The pause you add where you comments out my fix for object that should open in Photoshop but fail to open.  I test to see if placeLayerEditContent  created the temp work file. If the file exist I open the work document.     If the object work document does not exista or open then my open smart object  function throws an error which is caught by my EditSmarObject function.  You commented that code out of the Open Smart Object function your function does not throw an error when the object does not open in Photoshop.

 

Your script will fail to work correct when ever a Smart Object fails to open in Photoshop.  If a template has  a smart object layer the has Vector or RAW object your script will fail.

 

If your Smart Object is a Photoshop Object my code you commented out is design to open the temp Work  File created by Photoshop containing the objects content but did not open in Photoshop.  I have only seen that happen for one smart object in a template some posted here. 

 

You are not createing a CEP extension that can multi task.  In you script Photoshop steps should execute in sequencs.  If you use placeLayerEditContent  on as smart object layer that object the will open in photoshop that step is not complete till the document open in Photoshop.  If the Object will open in AI  the placeLayerEditContent step is complete once Photoshop passes the temp work file to your system to open. The file will open is some other application or fail to be open if there is no assocated application.  So you will not be able to work on the object to update the smart objects content if its not open in Photoshop..

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
Advocate ,
Jan 02, 2021 Jan 02, 2021

Copy link to clipboard

Copied

@JJMack 

 

thanks again for trying to explain your approach. I dont have problems with the placing, my files are smaller than in resolutuion when placed, thats why get doc bounds works in this case.

 

I also noticed that when using scriptlistner, photoshop actually runs another command after the editplaced. I was thinking of doing that but didnt know a method how to get the proper temp dir. I saw your implementation and that is quite nice. However when using it still runs code before the document is actually open. The edut command is given and i return a true state, only when its try should it do the rest of the steps. But it receives true and does the placement of files but still on the main doc. After the script has run or is near the end, only then is that smartobject opened. I found a different script which saves all placed smartobjects, that also uses editplaced and then when its open it saves it as a psd.

I will check that one and try to understand why the save command does run in the correct order. In that version it saves the opened smartobject after its opened. It runs a save command after the editplaced. Im not sure why in my case the place command keeps running before the smartobject is actually opened.

 

Using you version it keeps returning cant open the doc. But that is false, it does open but it looks like the ui is slower or so. That why i showed that synchronous vs asynchronous image. I have the feeling its running more functions almost at the same time. I returns true but the document is not yet open at that point. I got a workaround working which opens the smartobject before we run the script. I then switch back and forth between the 2 docs, that works but isnt as clean as i would want it to be

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 ,
Jan 03, 2021 Jan 03, 2021

Copy link to clipboard

Copied

The thing is Photoshop commands should be synchronous not be run in separate task  asynchronously that would requite a script or action to synchronize processing that needs to be done in sequence.   I saw problem in CS6  Photoshop version 13.0 where Photoshop operating was not  synchronize that cause Script and actions that process multiple document would fail sometimes because the was no active  document where the step executed the required a active document Photoshop had bot finished switching documents so the steps would fails for they were not available for execution there was no Active Document. 

 

You noticed that when using scriptlistner, photoshop actually runs another command after the editplaced. I only saw that happen for the Smart Object Layer in one template someone posted in a thread in this forum.   All of my template  object opened with editplaced without and additional command.   The addition command I saw the scriptlistener record for the one template object was an open for the temp work file Photoshop created for the object.   So I added that open to my open smart object function if the was no document switch.   The code I add works on a Window PC I think it should work on a Mac.  However it may not work if the Object is a vector or raw object  Photoshop doesx]x not directly support Camera RAW file and Vector Image Files.    My mockup script test smart object  layer object type it they contain a RAW or Vector object my script will display a message that object is nit supported and  bypass editing those templates smart object layers.    The Code I added to Open Smart Object test to see if Photoshop has switched documents.  If the document switch did not occur I try to open the work document that editplaced should have created if the work file exists. I again test if the document switch happens. if not I fail with smart object did mot open..

 

If you feel your problem is opening the object is just taking long time you should change your waitMoment() function to wait for the document switch to happen.   However, I feel your problem is more likely that you object is either a not Photoshop object its a RAW or Vector File or the open work file the extra command is needed.

 

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
Advocate ,
Jan 03, 2021 Jan 03, 2021

Copy link to clipboard

Copied

@JJMack 

 

thanks again JJMack for trying to help, much appreciated. The smartobject layer is a layer converted to smartobject, it has no physical link or path. Its is a PSB file which is the default Photoshop uses when converting layers into smartobjects. All the code ive added is from scriptlistner and is placed one after the other. The check you added seems to be failing in my case because the script is faster than the GUI of photoshop. 

I also tried adding app.refresh, wait and sleep. None of these seem to help to update the GUI and show the opening of the smartobject before the script continuous. Using your functions from your template files kept returning an error. I find this strange, i mean i know what file the smartobject is, i even did extra check to make sure irs either PSD or PSB, it also shows its a PSB in the properties panel.

 

What i find strange is that in the other script i found, which has about the same base of looping over layers and then use a editplacedcontent and then save as PSD does run just fine. I dont see the GUI change that much, but it saves all files properly. Could it be the place linked cant be used properly in this instance?

 

Your template file opens and closes all the files, is that correct? Perhaps that is the only case possible here, but im not very fond of that because you loose time because it needs to open and read documents each time.

 

I will try again and see if i can add the waiting at a different location in the script. Ive tried so many locations and still have not found the correct approach.

 

PS im testing on both Windows and OSX, the difference is that Windows is 2021 and OSX 2018. I do notice that the Windows version act really strange. Each time i close a document it looks like the GUI is freezing, for 1-2 seconds i keep seeing all the layer from and already closed document. Perhaps its my system but that would be weird. I mean this is a brand new AMD Ryzen 7 machine. I did do some googling on this 2021 version and found quite some posts about people stating its lagging. Perhaps thats causing the issue. What lots of people state is what im experiencing as well, i believe. The GUI feels like its freezing up 1-2 seconds or so 

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 ,
Jan 03, 2021 Jan 03, 2021

Copy link to clipboard

Copied

Please post  one of your templates you are having issues with.  It would like to see if I can make it compatible with my scripts so I can test it with my mockup scripts on windows.  I'm not having problems on my machine its old and slow. It just meets PS 2GHZ requirement  PS is not good using two processor and multitasking. My old dell workstation has two 6 core 2 GHz xeons.

 

Please upload a template and post a link to it.

 

I have many version of Windows PS installed.  PS 2021 has issues but My Scripts seem to work fine with 2021 ver 22.1

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
Community Expert ,
Jan 03, 2021 Jan 03, 2021

Copy link to clipboard

Copied

Something strange is going on.   I made a change to my Open Smart Object  where I was adding the open step that worked for me.  I put out an alert before adding the open.  If knew I would get the message on the first open of the smart object  but not the rest off the opens for the object in the batch the object opens  with the editobject command.  I waited a long time before dismissing the alert.  Low and behold the object temp work document opened before I added the open command.  When I dismissed the alert the Open I added fails because it was open.  

 

So tried change the function to wait for the editobject to eventualy switch document.  Without putting out the  pausing alert.   I tried

 

while ( current == app.activeDocument) app.refresh();

 

The work file document never opened

 

With the pause alert and waiting it does open and Photoshop swatches the document for the script.

This worked it tool a long time for the object to open adding the open performed better.

 

////// open smart object //////
function openSmartObject (theLayer) {
	current = app.activeDocument;
	if (theLayer.kind == "LayerKind.SMARTOBJECT") {
		runMenuItem(stringIDToTypeID('placedLayerEditContents'));
		if( current == app.activeDocument) {
			alert("pause");
			if( current != app.activeDocument) return app.activeDocument;
			alert("Adding open step");
			
			try {         
				var r = new ActionReference();     
				r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("smartObject"));  
				r.putIdentifier(stringIDToTypeID("layer"), theLayer.id);  
				var name = executeActionGet(r).getObjectValue(stringIDToTypeID("smartObject")).getString(stringIDToTypeID("fileReference"));         
				}  
			catch (e) { throw theLayer + " Smart Object Did not Open"; }  
			var workFile = new File(Folder.temp + "/" +  name);  // May work for both Windows and Mac
			if (workFile.exists) app.open(File(workFile));
			if ( current == app.activeDocument) throw theLayer + " Smart Object Did not Open";
		}
	}
	return app.activeDocument;
};

 

 

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
Advocate ,
Jan 03, 2021 Jan 03, 2021

Copy link to clipboard

Copied

@JJMack 

 

thanks once more for taking the time to look at it. I also had the same idea what you did with the while loop, but its goes into never ending loop. The script simply runs to fast for the GUI to even do anything. I tried a couple variations like if doc lenght isnt 2 then rerun the same function. That also goes into this never ending loop and i need to escape running script and in some cases even need force end photoshop because i cant get the script to stop.

 

PS i forgot to mention it earlier, your open smartobject function also throws this error. There i something not correct in the code, perhaps its missing curly brackets. I do see these one line if states before and sometimes they work. However i think its "throw" which is causing this error. Is this perhaps because i use the extension JSX vs JS?!


this is the error i get when adding your open smartobject functionthis is the error i get when adding your open smartobject function

 

Ive started a fresh new file with some test code in there to check if the editcontent works. PS it will always work if you an alert in there, somehow when i use that the GUI does update properly. But running file without will not run the script properly.

 

In this current state, your function throws a script error which we see in the image above.

 

The way i run this is have the mockup, so the PSD with the phone. I select the layer which is red (smartobject). I run the script, it will prompt you to select images, For a test i made those screen image in that zip file. Select one or a couple. It will then prompt for an export folder. For now ive turned of the save function since the main function doesnt even run properly. 

#target photoshop


var docRef = app.activeDocument;
var actLayer = docRef.activeLayer;


function cTID(s) {
    return app.charIDToTypeID(s);
};

function sTID(s) {
    return app.stringIDToTypeID(s);
};




////// open smart object //////
function openSmartObject(theLayer) {
    current = app.activeDocument;
    alert(theLayer)
    if (theLayer.kind == "LayerKind.SMARTOBJECT") {
        runMenuItem(stringIDToTypeID('placedLayerEditContents'));
        if (current == app.activeDocument) {
            try {
                var r = new ActionReference();
                r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("smartObject"));
                r.putIdentifier(stringIDToTypeID("layer"), theLayer.id);
                var name = executeActionGet(r).getObjectValue(stringIDToTypeID("smartObject")).getString(stringIDToTypeID("fileReference"));
            } catch (e) {
                throw theLayer + " Smart Object Did not Open";
            }
            var workFile = new File(Folder.temp + "/" + name); // May work for both Windows and Mac
            if (workFile.exists) app.open(File(workFile));
            if (current == app.activeDocument) throw theLayer + " Smart Object Did not Open";
        }
    } else {
        alert(theLayer +" is not a smartobject");
    }
    return app.activeDocument
};



// Check if object is PS
// R-Bin - JJ Mack
// https://community.adobe.com/t5/photoshop/extendscript-photoshop-edit-contents-smart-layer/m-p/10706542#M273949
function objectIsPsObject(SOlayer) {
	//Thanks to r-bin
	var ext = smartobject_file_ext(SOlayer);  
    var rc = true;
	switch (ext)  
		{  
		case "nef":  
		case "cr3":  
		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 placeImage(newFile){
    // app.refresh(); // doesnt work
    // app.redraw();// doesnt work
    // waitMoment();
    // $.sleep(500)
    
    // Switch document
    // var desc111 = new ActionDescriptor();
    //     var ref13 = new ActionReference();
    //     ref13.putOffset( cTID('Dcmn'), 1 );
    // desc111.putReference( cTID('null'), ref13 );
    // desc111.putInteger( cTID('DocI'), 344 );
    // executeAction( cTID('slct'), desc111, DialogModes.NO );
    
    // Place images
    // alert(newFile)
    var desc174 = new ActionDescriptor();
    desc174.putInteger( cTID('Idnt'), 885 );
    desc174.putPath( cTID('null'), new File(newFile));
     desc174.putBoolean( cTID('Lnkd'), true );
    desc174.putEnumerated( cTID('FTcs'), cTID('QCSt'), cTID('Qcsa') );
        var desc175 = new ActionDescriptor();
        desc175.putUnitDouble( cTID('Hrzn'), cTID('#Pxl'), 0.000000 );
        desc175.putUnitDouble( cTID('Vrtc'), cTID('#Pxl'), 0.000000 );
    desc174.putObject( cTID('Ofst'), cTID('Ofst'), desc175 );
    desc174.putUnitDouble( cTID('Wdth'), cTID('#Prc'), 234.782609 ); // i know the scale > this will make the image fit the SO file
    desc174.putUnitDouble( cTID('Hght'), cTID('#Prc'), 234.697509 ); // i know the scale > this will make the image fit the SO file
    executeAction( cTID('Plc '), desc174, DialogModes.NO );

}
function exportMockupDesigns() {
    // Get OS
    // fromt "_LastLogEntry.jsx"
    isWindows = function() {
        return $.os.match(/windows/i);
    };
    isMac = function() {
        return !isWindows();
    };
    var osPath = (isMac() ? '/' : "/"); // resolve windows vs osx paths
    // alert(isMac())


    if (app.documents.length > 0) {
        var myDocument = app.activeDocument;
        var theName = myDocument.name.match(/(.*)\.[^\.]+$/)[1];
        var thePath = myDocument.path;
        var theLayer = myDocument.activeLayer;
        // jpg options;
        var jpgopts = new JPEGSaveOptions();
        jpgopts.embedProfile = true;
        jpgopts.formatOptions = FormatOptions.STANDARDBASELINE;
        jpgopts.matte = MatteType.NONE;
        jpgopts.quality = 8;
        // check if layer is smart object;
        if (theLayer.kind != "LayerKind.SMARTOBJECT") {
            alert("selected layer is not a smart object")
        } else if (objectIsPsObject(actLayer) != true) {
            alert("The SmartOjbect is not a PSB or PSD file")
            return 'cancel'; // quit, returning 'cancel' (dont localize) makes the actions palette not record our script
        } else {
            // select files;
            if ($.os.search(/windows/i) != -1) {
                var theFiles = File.openDialog("please select files", "*.psd;*.tif;*.jpg;*.jpeg;", true)
            } else {
                var theFiles = File.openDialog("please select files", getFiles, true)
            };
            // select Folder;
            // var theFolder = Folder.selectDialog("select folder");
            if (theFiles) {
                // var theFiles = theFolder.getFiles(/\.(jpg|tif|eps|psd|png)$/i);
                // Select destination folder
                var destinationFolder = Folder.selectDialog("Please select a destination folder");
                // work through the array;
                for (var m = 0; m < theFiles.length; m++) {
                    // replace smart object;
                    openSmartObject(theLayer);
                    // app.refresh()
                    // alert(editSO)
                    // waitMoment()
                    //  $.sleep(500)
                    // waitForRedraw();// notworking
                    placeImage(theFiles[m]);


                   // var theNewName = theFiles[m].name.match(/(.*)\.[^\.]+$/)[1];
                    //save jpg;
                   // myDocument.saveAs((new File(destinationFolder.toString() + "/" + theName + "_" + theNewName + ".jpg")), jpgopts, true);

                    // }
                }
            };
        }
    };

    ////// get psds, tifs and jpgs from files //////
    function getFiles(theFile) {
        if (theFile.name.match(/\.(psd|tif|png|jpg|jpeg)$/i) != null || theFile.constructor.name == "Folder") {
            return true
        };
    };
};
exportMockupDesigns();

 

 

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