Компьютерный форум OSzone.net  

Компьютерный форум OSzone.net (http://forum.oszone.net/index.php)
-   Вебмастеру (http://forum.oszone.net/forumdisplay.php?f=22)
-   -   Скрипт для Photoshop сохраняет русские имена файлов как ?????.jpg (http://forum.oszone.net/showthread.php?t=334143)

Archy_A@twitter 04-04-2018 18:10 2807035

Скрипт для Photoshop сохраняет русские имена файлов как ?????.jpg
 
Добрый день!

Имею вот такой замечательный скрипт для пережима изображений в Фотошопе.
Дописал в него рекурсию по сабфолдерам, дописал все расширения в один скрипт, дописал удаление уменьшенного файла, если он по факту не уменьшился, а увеличился (child.remove), но имею проблему.
Доставил алертов в разных местах, чтобы видеть, что происходит.

Но когда (если) попадаются файлы с русскими символами, то при их сохранении вместо "image1 - копия.jpg" файл сохраняется как "image1 - ?????.jpg".
Перепробовал уже и unescape(), и encode/decodeURI(). Я, наверное, не туда их вставляю или просто еще что-то не так делаю... Запутался.

В общем, буду признателен за подсказку (закоментировал свои попытки изменять имя сохраняемого файла и выделил болдом места собственно сохранения).

Код:

/*

// Open a given folder and compress all JPEG images with Tinify.
// Copyright (c) 2015 Voormedia B.V. All rights reserved.

<javascriptresource>
<menu>automate</menu>
<category>compression</category>
<name>$$$/TinifyFolderJPEGPNG/Menu=Compress Folder with JPEG and PNG Images...</name>
<eventid>B679042E-E418-4724-A313-5549AE8F2EC6</eventid>
</javascriptresource>

*/

function compressJPEGFile(file, percentage) {

    // Open the file without dialogs like Adobe Camera Raw
    var opener = new ActionDescriptor();
    opener.putPath(charIDToTypeID("null"), file);
    executeAction(charIDToTypeID("Opn "), opener, DialogModes.NO);

    // Select the opened document
    var document = app.activeDocument;

    // Change the color space to RGB if needed
    if (document.mode == DocumentMode.INDEXEDCOLOR) {
        document.changeMode(ChangeMode.RGB);
    }

    // Switch to 8 bit RGB if the image is 16 bit
    if (document.bitsPerChannel == BitsPerChannelType.SIXTEEN) {
        convertBitDepth(8);
    }

    // Choose the scale percentage
    if (percentage === undefined || percentage < 10 || percentage > 100) {
      percentage = 100;
    }

    // Compress the document
    var tinify = new ActionDescriptor();
    tinify.putPath(charIDToTypeID("In  "), file); /* Overwrite original! */
    tinify.putUnitDouble(charIDToTypeID("Scl "), charIDToTypeID("#Prc"), percentage);
    tinify.putEnumerated(charIDToTypeID("FlTy"), charIDToTypeID("tyFT"), charIDToTypeID("tyJP")); /* Force JPEG */

    var compress = new ActionDescriptor();
    compress.putObject(charIDToTypeID("Usng"), charIDToTypeID("tinY"), tinify);
    executeAction(charIDToTypeID("Expr"), compress, DialogModes.NO);

    document.close(SaveOptions.DONOTSAVECHANGES);
}

function compressPNGFile(file, percentage) {

    // Open the file without dialogs like Adobe Camera Raw
    var opener = new ActionDescriptor();
    opener.putPath(charIDToTypeID("null"), file);
    executeAction(charIDToTypeID("Opn "), opener, DialogModes.NO);

    // Select the opened document
    var document = app.activeDocument;

    // Change the color space to RGB if needed
    if (document.mode == DocumentMode.INDEXEDCOLOR) {
        document.changeMode(ChangeMode.RGB);
    }

    // Switch to 8 bit RGB if the image is 16 bit
    if (document.bitsPerChannel == BitsPerChannelType.SIXTEEN) {
        convertBitDepth(8);
    }

    // Choose the scale percentage
    if (percentage === undefined || percentage < 10 || percentage > 100) {
      percentage = 100;
    }

    // Compress the document
    var tinify = new ActionDescriptor();

// file.name = unescape(file.name); // Archy
// alert (file.name);

    tinify.putPath(charIDToTypeID("In  "), file); /* Overwrite original! */
    tinify.putUnitDouble(charIDToTypeID("Scl "), charIDToTypeID("#Prc"), percentage );
    tinify.putEnumerated(charIDToTypeID("FlTy"), charIDToTypeID("tyFT"), charIDToTypeID("tyPN")); /* Force PNG */

    var compress = new ActionDescriptor();
    compress.putObject(charIDToTypeID("Usng"), charIDToTypeID("tinY"), tinify);
    executeAction(charIDToTypeID("Expr"), compress, DialogModes.NO);

    document.close(SaveOptions.DONOTSAVECHANGES);
}


function convertBitDepth(bitdepth) {
    var id1 = charIDToTypeID("CnvM");
    var convert = new ActionDescriptor();
    var id2 = charIDToTypeID("Dpth");
    convert.putInteger(id2, bitdepth);
    executeAction(id1, convert, DialogModes.NO);
}

function compressPNGFolder(folder) {
    // Recursively open files in the given folder
    var children = folder.getFiles();
    var fs = folder.getFiles();
    var fo = 0;
    for (var i = 0; i < children.length; i++) {
        var child = children[i];
//alert (child.name);
//    child.name = decodeURI (children[i].name);
//alert (child.name);

        if ((child instanceof Folder)&&(child.name.slice(-1).toLowerCase() != ".")) {
        compressPNGFolder(child);
        } else {
            /* Only attempt to compress PNG files. */
            if (child.name.slice(-4).toLowerCase() == ".png") {
        fo = child.length;
                compressPNGFile(child);
        fs = folder.getFiles(decodeURI(child.name));
        alert ("Name: " + decodeURI(child.name) + " was: " + fo + " now: " + fs[0].length);
        if (fs[0].length > fo) {
            child.remove();
//            alert ("PNG Deleted: " + decodeURI(child.name) + "\nwas: " + fo + " now: " + fs[0].length);
        }
            } else
            /* Only attempt to compress JPG files. */
            if ((child.name.slice(-5).toLowerCase() == ".jpeg")||(child.name.slice(-4).toLowerCase() == ".jpg")) {
        fo = child.length;
                compressJPEGFile(child);
        fs = folder.getFiles(decodeURI(child.name));
        alert ("Name: " + decodeURI(child.name) + " was: " + fo + " now: " + fs[0].length);
        if (fs[0].length > fo) {
            child.remove();
//            alert ("JPG Deleted: " + decodeURI(child.name) + "\nwas: " + fo + " now: " + fs[0].length);
        }
            }
        }
    }
}

//if (confirm("Warning. You are about to compress all JPEG files in the chosen folder. This cannot be undone.\n\rAre you sure you want to continue?")) {
    try {
        // Let user select a folder
        compressPNGFolder(Folder.selectDialog("Choose a folder with JPEG-PNG images to compress with TinyJPG-PNG"));
        alert("All JPEG-PNG files compressed.");
    } catch(error) {
        alert("Error while processing: " + error);
    }
//}


Iska 05-04-2018 00:23 2807085

Цитата:

Цитата Archy_A@twitter
Но когда (если) попадаются файлы с русскими символами, то при их сохранении вместо "image1 - копия.jpg" файл сохраняется как "image1 - ?????.jpg".
Перепробовал уже и unescape(), и encode/decodeURI(). Я, наверное, не туда их вставляю или просто еще что-то не так делаю... Запутался. »

Судя по беглому поиску — проблема не в Вашем коде, а в разработчиках Adobe. Рекомендуют такой обходной путь: сохранять результат во временный файл, затем переименовывать/переносить его на место исходного (см., например, комментарии к Photoshop script. Сохранение файлов с использованием иерархии групп - Login|off Nick).

Archy_A@twitter 05-04-2018 10:18 2807119

Это сторонний плагин, это даже не Adobe... Но спасибо, попробую.

Iska 05-04-2018 14:10 2807184

Archy_A@twitter, тем хуже, полагаю.


Время: 02:16.

Время: 02:16.
© OSzone.net 2001-