импортировать определенные форматы файлов из папки в Illustrator через скрипт - PullRequest
1 голос
/ 23 октября 2019

Я нашел этот скрипт в сети, который почти то, что я ищу, но его нужно адаптировать, и я не могу заставить его работать.

    if (selectedFolder) {
        myDocument = app.documents.add();

        var firstImageLayer = true;
        var newLayer ;
        var thisPlacedItem;

        // create document list from files in selected folder
        var imageList = selectedFolder.getFiles();

        for (var i = 0; i < imageList.length; i++) {
            // open each document in file list
            if (imageList[i] instanceof File) {
                // get the file name
                var fName = imageList[i].name.toLowerCase();
                // check for supported file formats
                //if( (fName.indexOf(".eps") == -1) ) {
                if( (fName.indexOf(".tga") == -1) && (fName.indexOf(".png") == -1)) {
                    // skip unsupported formats
                    continue;
                } else {
                    if( firstImageLayer ) {
                        newLayer = myDocument.layers[0];
                        firstImageLayer = false;
                    } else {
                        newLayer = myDocument.layers.add();
                    }
                   // Give the layer the name of the image file
                   newLayer.name = fName.substring(0, fName.indexOf(".") );

                   // Place the image on the artboard
                   thisPlacedItem = newLayer.placedItems.add()
                   thisPlacedItem.file = imageList[i];

                   switch( placement9pointAlignment ) {
                        default :
                            break;
                        case "ul" : 
                            thisPlacedItem.top = myDocument.height;
                            thisPlacedItem.left = 0;
                            break;
                        case "ml" : 
                            thisPlacedItem.top = myDocument.height / 2 + thisPlacedItem.height / 2;
                            thisPlacedItem.left = 0;
                            break;
                        case "ll" : 
                            thisPlacedItem.top = thisPlacedItem.height;
                            thisPlacedItem.left = 0;
                            break;
                        case "ur" : 
                            thisPlacedItem.top = myDocument.height;
                            thisPlacedItem.left = myDocument.width - thisPlacedItem.width;
                            break;
                        case "mr" : 
                            thisPlacedItem.top = myDocument.height / 2 + thisPlacedItem.height / 2;
                            thisPlacedItem.left = myDocument.width - thisPlacedItem.width;
                            break;
                        case "lr" : 
                            thisPlacedItem.top = thisPlacedItem.height;
                            thisPlacedItem.left = myDocument.width - thisPlacedItem.width;
                            break;
                        case "um" : 
                            thisPlacedItem.top = myDocument.height;
                            thisPlacedItem.left = myDocument.width / 2 - thisPlacedItem.width / 2;
                            break;
                        case "mm" : 
                            thisPlacedItem.top = myDocument.height / 2 + thisPlacedItem.height / 2;
                            thisPlacedItem.left = myDocument.width / 2 - thisPlacedItem.width / 2;
                            break;
                        case "lm" : 
                            thisPlacedItem.top = thisPlacedItem.height;
                            thisPlacedItem.left = myDocument.width / 2 - thisPlacedItem.width / 2;
                            break;
                   }
                }
            }
        }

        if( firstImageLayer ) {
            // alert("The action has been cancelled.");
            // display error message if no supported documents were found in the designated folder
            alert("Sorry, but the designated folder does not contain any recognized image formats.\n\nPlease choose another folder.");
            myDocument.close();
            importFolderAsLayers(getFolder());
        }

    } else {
        // alert("The action has been cancelled.");
        // display error message if no supported documents were found in the designated folder
        alert("Rerun the script and choose a folder with images.");
        //importFolderAsLayers(getFolder());
    }
}

//Start the script off
importFolderAsLayers( getFolder() );

Я хочу иметь возможностьвыбрать папку и сделать так, чтобы она импортировала только файлы .tga или .png. если есть другие форматы файлов, я хочу, чтобы они игнорировались.

проблема с этим скриптом в том, что он ищет по имени файла, а не по расширению. Обычно это будет работать нормально, но я часто получаю файлы .tga вместе с копией в формате JPEG с именем image_01.tga.jpeg

Это проблема, потому что теперь, когда я использую скрипт, он импортирует tga и jpeg!

Кто-нибудь знает, как я мог адаптировать этот скрипт, чтобы он выполнял поиск именно по расширению?

1 Ответ

0 голосов
/ 31 октября 2019

Метод getFiles(), который вы используете в строке, которая читает;

var imageList = selectedFolder.getFiles();

принимает аргумент mask - это по сутиШаблон RegExp.

Если вы измените эту строку на;

var imageList = selectedFolder.getFiles(/\.(tga|png)$/i);

, это будет гарантировать, что список файлов, назначенных переменной imageList, будет только файлом, который заканчивается на .tga,.TGA, .png или .PNG.

Тогда вам не нужно выполнять какую-либо фильтрацию типов файлов в цикле for.

...