我在Mobile01的相機板看到 笨蛋也會用的縮圖軟體Photo Resize,覺得非常不錯因此在我的 blog 也做了操作的介紹,當時我就想如果在Mac有這樣的縮圖軟體不是很棒嗎?
因此我找到以前這位 robg 寫的 Drag-and-drop script to quickly resize any image ,你只要將Applescript存成應用程式放在桌面,將照片拖放到icon,就會自動將照片縮為寬120pix的圖像更名存回原目錄。
那如果我要像PhotoResize那樣,在程式名稱後面加上數字,如800,就縮成寬800pix 的圖可不可以呢?
實作:
那我先講一下怎樣將樣式比對出來,先講第一種比較笨的方法,然後再講樣式比對的方式
第一種方式:
如果我在桌面建立一個空檔案叫resize600.app,我要怎樣知道這裡面含有600這3個數字?

我先輸入 ls ~/Desktop/resize*
找出的結果是 /Users/jkchang/Desktop/resize600.app*
然後用 cut 指令ls ~/Desktop/resize*|cut -d . -f 1 將 .app 前面取出來
(將句點分作左右兩個欄位,如果是 cut -d . -f 2 則得到 app*)
結果: /Users/jkchang/Desktop/resize600
然後再用 cut 指令將 / 符號的第5個欄位取出來 ls ~/Desktop/resize*|cut -d . -f 1|cut -d / -f 5
結果: resize600
這時已經將resize600拿到了,剩下就是去掉resize剩600,一樣用cut 將第7個字以後的取出
ls ~/Desktop/resize*|cut -d . -f 1|cut -d / -f 5|cut -b 7-
結果: 600
第二種方式(樣式比對):

得到結果一樣是600
關於shell的樣式比對可以參考shell的書籍或是你用perl正規式來作也行!
接下來我把程式碼加入Applescript中

將增加的script 放在 to rescale_and_save(this_item) 後面,取得的數字放入變數 d 中:(--後面當作是註解)
--我增加的功能
--方式一
--set c to do shell script "ls ~/Desktop/resize* | cut -d . -f 1 | cut -d / -f 5 | cut -b 7-"
--方式二
set c to do shell script "a=`ls ~/Desktop/resize*`;b=${a%%.*};c=${b##*/};echo $c|cut -b 7-"
--display dialog c
set d to c as integer
class of d
剛開始你可以將display dialog c前面的--拿掉,在你將照片拖入程式icon時會顯示出多少像素的數字來驗證是否正確,
將Applescript存成應用程式於桌面,檔案名稱叫resize600。


這時你將照片拖入程式icon時會出現600的框框

然後將set the target_width to 120 改為 set the target_width to d
還有存檔時原本是在檔案名稱加上"scaled."
tell application "Finder" to set new_item to ¬
(container of this_item as string) & "scaled." & (name of this_item)
save this_image in new_item as typ
我改為檔案名稱前加上600_
tell application "Finder" to set new_item to ¬
(container of this_item as string) & c & "_" & (name of this_item)
save this_image in new_item as typ
執行後的樣子:

縮圖放回原檔案夾內並在檔案名稱前加上600_

如此一來你只要修改成想要縮圖的寬度那丟進的檔案就會按你輸入的來進行縮圖。
後記:
1.我這程式目前只能放在桌面,而且當檔案夾名稱是含有中文時會有問題。
2.修改後的Applescript如下,紅色字體部份是修改後的:
~~~~
on open some_items
repeat with this_item in some_items
try
rescale_and_save(this_item)
end try
end repeat
end open
to rescale_and_save(this_item)
--我增加的功能
--set c to do shell script "ls ~/Desktop/resize* | cut -d . -f 1 | cut -d / -f 5 | cut -b 7-"
set c to do shell script "a=`ls ~/Desktop/resize*`;b=${a%%.*};c=${b##*/};echo $c|cut -b 7-"
--display dialog c
set d to c as integer
class of d
tell application "Image Events"
launch
set the target_width to d
-- open the image file
set this_image to open this_item
set typ to this_image's file type
copy dimensions of this_image to {current_width, current_height}
if current_width is greater than current_height then
scale this_image to size target_width
else
-- figure out new height
-- y2 = (y1 * x2) / x1
set the new_height to (current_height * target_width) / current_width
scale this_image to size new_height
end if
tell application "Finder" to set new_item to ¬
(container of this_item as string) & c & "_" & (name of this_item)
save this_image in new_item as typ
end tell
end rescale_and_save