Photoshop javascript批量替换文件夹中的智能图层并调整其大小

时间:2018-10-11 12:47:00

标签: javascript css photoshop adobe-illustrator photoshop-script

我正在尝试找出如何在photoshop中使用javascript,但是即使我在代码中找不到逻辑错误,也无法正常工作。

我有1000多个具有不同尺寸的images / .ai文件的文件夹。我需要在枕头上保存这些图像并另存为.jpeg。 我选择智能图层并运行脚本以选择图像,然后正确保存它们。唯一的问题是图像的大小调整和定位无法正常工作。 如果我手动放置图像,则可以正常使用,但不能与脚本一起使用。

如果宽度大于高度,则应将宽度设置为1200 px,并据此计算高度。 (反之亦然)并放置在图层的中间。

  1. 如何调整大小和位置?
  2. 是否可以选择其中包含图像的文件夹而不是选择图像?
  3. 当要在模型中更改2个智能层而不是1个时,如何处理?

任何人都知道问题出在哪里吗? 非常感谢您的帮助!

 // Replace SmartObject’s Content and Save as JPG
// 2017, use it at your own risk
// Via @Circle B: https://graphicdesign.stackexchange.com/questions/92796/replacing-a-smart-object-in-bulk-with-photoshops-variable-data-or-scripts/93359
// JPG code from here: https://forums.adobe.com/thread/737789

#target photoshop
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;
    jpgSaveOptions = new JPEGSaveOptions();  
    jpgSaveOptions.embedColorProfile = true;  
    jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;  
    jpgSaveOptions.matte = MatteType.NONE;  
    jpgSaveOptions.quality = 8;   
    // Check if layer is SmartObject;
    if (theLayer.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;*.ai", true)
        } else {
            var theFiles = File.openDialog("please select files", getFiles, true)
        };
};
(function (){
    var startRulerUnits = app.preferences.rulerUnits;  
    app.preferences.rulerUnits = Units.PIXELS;  
    var bounds = activeDocument.activeLayer.bounds;  
    var height = bounds[3].value - bounds[1].value;
    var width = bounds[2].value - bounds[0].value;
if (height > width){ 
    var newSize1 = (100 / width) * 800;  
    activeDocument.activeLayer.resize(newSize1, newSize1, AnchorPosition.MIDDLECENTER);
    app.preferences.rulerUnits = startRulerUnits;  
    }  
else{
    var newSize2 = (100 / height) * 800;  
    activeDocument.activeLayer.resize(newSize2, newSize2, AnchorPosition.MIDDLECENTER);
    app.preferences.rulerUnits = startRulerUnits;      
    } 
})();
        if (theFiles) {
            for (var m = 0; m < theFiles.length; m++) {
                // Replace SmartObject
                theLayer = replaceContents(theFiles[m], theLayer);
                var theNewName = theFiles[m].name.match(/(.*)\.[^\.]+$/)[1];
                // Save JPG
                myDocument.saveAs((new File(thePath + "/" + theName + "_" + theNewName + ".jpg")), jpgSaveOptions, true,Extension.LOWERCASE);
            }
        }
    };
// Get PSDs, TIFs and JPGs from files
function getFiles(theFile) {
    if (theFile.name.match(/\.(psd|tif|jpg)$/i) != null || theFile.constructor.name == "Folder") {
        return true
    }
};
// Replace SmartObject Contents
function replaceContents(newFile, theSO) {
    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);
    return app.activeDocument.activeLayer
};

我已附上2张图片。 1它看起来像什么,2脚本输出什么 Correct Wrong

1 个答案:

答案 0 :(得分:0)

  1. 替换后的图像必须与智能对象具有相同的分辨率。
  2. 您可以在代码中声明文件夹路径。如果仍要手动选择路径,则可以在路径中选择一张图像,然后提取父文件夹路径。
  3. 您可以递归浏览文档中的所有层,并提取所有要替换的智能对象。

您可能希望函数以递归方式遍历文档中的所有图层

function browseLayer(layer, fn) {
    if (layer.length) {
        for (var i = 0; i < layer.length; ++i) {
            browseLayer(layer[i], fn)
        }
        return;
    }

    if (layer.layers) {
        for (var j = 0; j < layer.layers.length; ++j) {
            browseLayer(layer.layers[j], fn);
        }
        return;
    }
    //apply this function for every layer
    fn(layer)
}

获取文档中的所有智能对象

const smartObjects = [];
//The smart objects can be visit twice or more
//use this object to mark the visiting status
const docNameIndex = {};

const doc = app.open(new File("/path/to/psd/file"));

browseLayer(doc.layers, function (layer) {
    //You cannot replace smart object with position is locked
    if (layer.kind == LayerKind.SMARTOBJECT && layer.positionLocked == false) {

        smartLayers.push(layer);

        doc.activeLayer = layer;

        //open the smart object
        executeAction(stringIDToTypeID("placedLayerEditContents"), new ActionDescriptor(), DialogModes.NO);

        //activeDocument is now the smart object
        const docName = app.activeDocument.name;

        if (!docNameIndex[docName]) {

            docNameIndex[docName] = true;

            smartObjects.push({
                id: layer.id,
                name: layer.name,
                docName: docName,
                width : app.activeDocument.width.as('pixels'),
                height : app.activeDocument.height.as('pixels'),
                resolution : app.activeDocument.resolution //important
            });
        }
        //reactive the main document
        app.activeDocument = doc;
    }

});

我假设您需要替换两个智能对象,用于替换的图像以相同的名称存储在不同的文件夹中。

smartObjects[0].replaceFolderPath = "/path/to/folder/1";
smartObjects[1].replaceFolderPath = "/path/to/folder/2";
//we need temp folder to store the resize images
smartObjects[0].tempFolderPath = "/path/to/temp/folder/1";
smartObjects[1].tempFolderPath = "/path/to/temp/folder/2";

Ex:第一次迭代会将smartObjects[0]替换为"/path/to/folder/1/image1.jpg",并将smartObjects[1]替换为"/path/to/folder/image1.jpg"

现在按照智能对象的属性调整所有图像的大小

smartObjects.forEach(function(smartObject){

    //Get all files in the folder
    var files = new Folder(smartObject.replaceFolderPath).getFiles();

    //Resize all the image files
    files.forEach(function (file) {

        var doc = app.open(file);

        doc.resizeImage(
            new UnitValue(smartObject.width + ' pixels'),
            new UnitValue(smartObject.height + ' pixels'),
            smartObject.resolution
        );

        //save to temp folder
        doc.saveAs(
            new File(smartObject.tempFolderPath + "/" + file.name),
            new PNGSaveOptions(),
            true
        );

        doc.close(SaveOptions.DONOTSAVECHANGES)
    });

});

最后,替换智能对象

//get list of file again
var files = new Folder(smartObject.replaceFolderPath).getFiles();

files.forEach(function(file){

    var fileName = file.name;

    smartObjects.forEach(function(smartObject){

        //active the window opening the smart object
        app.activeDocument = app.documents.getByName(args.documentName);

        var desc = new ActionDescriptor();
        desc.putPath(charIDToTypeID("null"), new File(smartObject.tempFolderPath + "/" + fileName));

        executeAction(stringIDToTypeID( "placedLayerReplaceContents" ), desc, DialogModes.NO);

    });

    //Now export document
    var webOptions = new ExportOptionsSaveForWeb();
    webOptions.format = SaveDocumentType.PNG; // SaveDocumentType.JPEG
    webOptions.optimized = true;
    webOptions.quality = 100;

    doc.exportDocument(new File("/path/to/result/folder" + file.name), ExportType.SAVEFORWEB, webOptions);

});

现在您可以关闭所有打开的智能对象

smartObjects.forEach(function (s) {
    app.documents.getByName(r.docName).close(SaveOptions.DONOTSAVECHANGES);
});