0

是否可以使用一组 Ruby 命令更改 Mac 文件夹的图标?我相信 OSX 需要 .icon 文件存在于修改后的文件夹中,也许有一种将 jpg 或 png 转换为 .icon 标准的特定方法?

- 编辑(工作解决方案。需要 ImageMagick 和OSXUtils) *注意,对于我的应用程序,我打算设置文件夹图标。这完全有可能也适用于文件。

def set_icon image, folder

        # Convert to absolute paths and setup
        image = File.expand_path image
        folder = File.expand_path folder
        dim = 512
        thumb = folder + '/'+ 'thumb.png' # PNG supports transparency
        icon = folder + '/'+ 'icon.icns'

        # Convert original to thumbnail
        system "convert '#{ image }' -quiet -thumbnail '#{dim}x#{dim}>' \
          -background none -gravity center -extent #{dim}x#{dim} '#{ thumb }'"

        # Set icon format. Causes 'libpng warning: Ignoring attempt to set cHRM RGB triangle with zero area'
        system "sips -s format icns '#{ thumb }' --out '#{ icon }'"

        # Set the icon
        system "seticon -d '#{ icon }' '#{ folder }'"

        # Cleanup
        FileUtils.rm thumb
        FileUtils.rm icon
end
4

1 回答 1

1

自从我使用它们以来已经有好几年了,但是 .icon 文件的格式被 Apple 的文档和维基百科记录了。

如果我没记错的话,这个名字有一个尾随"\r",使它更难输入,但这很容易从代码中处理。

您应该能够使用正常的File.rename方法将 .icon 文件移动到文件夹中,并且 Finder 应该会做正确的事情。


查看您的代码,我会做一些不同的事情:

require 'fileutils'
def set_icon image, folder

    # Convert to absolute paths and setup
    image = File.expand_path image
    folder = File.expand_path folder
    temp = File.join(folder, 'temp2' + File.extname(image))

    # Copy image
    FileUtils.cp(image, temp)

    # Take an image and make the image its own icon
    system "sips -Z 512 -i #{ temp }"

    # Extract the icon to its own resource file
    system "DeRez -only icns #{ temp } > tmpicns.rsrc"

    # Append a resource to the folder you want to icon-ize
    system "Rez tmpicns.rsrc -o $'#{ folder }/Icon\r'"

    # Use the resource to set the icon.
    system "SetFile -a C #{ folder }"

end

而不是依靠sprintfor %("format") 来构建字符串,而是使用简单的插值。sprintf当您需要强制列宽并将值强制转换为不同的表示形式时,字符串非常有用,但是当您插入未格式化的单个值时,它们就显得多余了。

sips有这个选项,看起来很有希望,但在手册页中没有很好地记录:

 -i
 --addIcon
       Add a Finder icon to image file.

此外,Stack Overflow 的同级网站“Ask Different”有“为什么用 sip 将图像设置为自己的图标会导致图标模糊?还有其他选择吗? ”、“如何通过 CLI 为目录设置图标? ”和“更改使用“终端”的文件或文件夹图标,看起来很有用。

于 2013-07-03T23:35:33.367 回答