用Ruby更改mac文件夹图标



是否可以使用一组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

我已经多年没有使用它们了,但苹果的文档和Wikepedia记录了.icon文件的格式。

如果我没记错的话,这个名称后面有一个"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 }/Iconr'"
    # Use the resource to set the icon.
    system "SetFile -a C #{ folder }"
end

与其依赖sprintf%("format")来构建字符串,不如使用简单的插值。当您需要强制列宽并将值强制转换为不同的表示形式时,sprintf字符串非常好,但当您插入一个未格式化的值时,它们会被过度使用。

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

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

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

最新更新