Automator / AppleScript: пакетное вращение и обрезка (и сжатие) - PullRequest
0 голосов
/ 15 апреля 2020

Я пытаюсь создать рабочий процесс с Automator (или AppleScript), который выполняет следующие действия с несколькими изображениями одновременно (я нахожусь на Ма c, как вы можете догадаться).

  1. Поворот изображения в альбомную ориентацию, если оно портретное
  2. Обрезка изображения до 2048x1536 пикселей (без добавления черных полей)
  3. (если возможно: сжатие изображения для уменьшения размера файла)

Кто-нибудь знает, как этого добиться? Было бы здорово иметь все это в одном скрипте / приложении Automator, потому что у меня есть несколько тысяч изображений, которые нужно вращать и обрезать.

1 Ответ

0 голосов
/ 18 апреля 2020

Отнесите этот скрипт к тому факту, что я застрял дома и мне скучно. Также кредит Apple, так как я использовал части одного из их файлов шаблонов (Файл → Новый из шаблона → Капли → Шаблон обработки файла рекурсивного изображения) ?

Вы запускаете следующий скрипт двумя способами:

  • Прямо из редактора сценариев: запустите его, и он попросит вас выбрать папки для обработки
  • В виде капли: сохраните сценарий как приложение (выберите «приложение» в раскрывающемся меню «формат») на экране «Сохранить»), затем перетащите файлы и папки на значок

. Этот сценарий запускает иерархию папок в поисках файлов изображений, а когда находит их, он вращается, расширяется и Обрезает по мере необходимости, чтобы получить изображение размером 2048x1536, которое оно сохраняет в той же папке с исходным именем файла с добавленным тегом «- munged».

Прежде чем пытаться это сделать, обязательно сделайте резервную копию папок с изображениями. Вещи редко работают идеально на первом проходе.

property type_list : {"JPEG", "TIFF", "PNGf", "8BPS", "BMPf", "GIFf", "PDF ", "PICT"}
property extension_list : {"jpg", "jpeg", "tif", "tiff", "png", "psd", "bmp", "gif", "jp2", "pdf", "pict", "pct", "sgi", "tga"}
property typeIDs_list : {"public.jpeg", "public.tiff", "public.png", "com.adobe.photoshop-image", "com.microsoft.bmp", "com.compuserve.gif", "public.jpeg-2000", "com.adobe.pdf", "com.apple.pict", "com.sgi.sgi-image", "com.truevision.tga-image"}

property target_height : 1536
property target_width : 2048
property marker_text : " - munged"

-- choose folders to process if the script is run from scriopt editor
on run
    set these_items to choose folder with prompt "Choose folders to process" with multiple selections allowed
    repeat with this_item in these_items
        process_item(POSIX path of this_item)
    end repeat
end run

-- dropped files and folders enter the stream here
on open these_items
    repeat with this_item in these_items
        process_item(POSIX path of this_item)
    end repeat
end open

-- this sub-routine parces folders to find image files
on process_item(this_item)
    tell application "System Events"
        set this_disk_item to disk item this_item
        -- skip invisible items and processed output
        if visible of this_disk_item is false or name of this_disk_item contains marker_text then return
        if class of this_disk_item is folder then
            set contents_list to disk items of this_disk_item
            repeat with an_item in contents_list
                my process_item(POSIX path of an_item)
            end repeat
        else
            try
                set this_extension to the name extension of this_disk_item
            on error
                set this_extension to ""
            end try
            try
                set this_filetype to the file type of this_disk_item
            on error
                set this_filetype to ""
            end try
            try
                set this_typeID to the type identifier of this_disk_item
            on error
                set this_typeID to ""
            end try
            if (class of this_disk_item is not alias) and ¬
                ((this_filetype is in the type_list) or ¬
                    (this_extension is in the extension_list) or ¬
                    (this_typeID is in typeIDs_list)) ¬
                    then
                my process_image(POSIX path of this_disk_item)
            end if
        end if
    end tell
end process_item

-- this sub-routine processes image files 
on process_image(this_image_path)
    tell application "Image Events"
        set revised_image to open this_image_path
        set {w, h} to dimensions of revised_image
        set desired_scale to target_height / target_width
        if w < h then
            -- portrait mode; rotate
            rotate revised_image to angle 270.0
            -- need to reverse dimensions; image events seems to be working off the saved file, not the rotated image
            set actual_scale to w / h
            if actual_scale > desired_scale then
                scale revised_image by factor target_width / h
            else
                scale revised_image by factor target_height / w
            end if
        else
            set actual_scale to h / w
            if actual_scale > desired_scale then
                scale revised_image by factor target_width / w
            else
                scale revised_image by factor target_height / h
            end if
        end if

        crop revised_image to dimensions {target_width, target_height}

        set new_file_name to my edited_file_name(name of revised_image)
        save revised_image as JPEG in ((POSIX path of (location of revised_image)) & "/" & new_file_name) with compression level medium with icon
        close revised_image
    end tell
end process_image

-- routine to add marker text to revised file names, so we don't overwrite the original data
on edited_file_name(the_file_name)
    set tid to my text item delimiters
    set my text item delimiters to "."
    set bits_list to text items of the_file_name
    if (count of bits_list) > 1 then
        set (item -2 of bits_list) to contents of (item -2 of bits_list) & marker_text
    else
        set (item 1 of bits_list) to contents of (item 1 of bits_list) & marker_text
    end if
    set revised_name to bits_list as text
    set my text item delimiters to tid
    return revised_name
end edited_file_name
...