Tuesday, September 27, 2016

AppleScript: iTunes: Get All the Artwork of Current Playlist

on replace_chars(this_text, search_string, replacement_string)
set AppleScript's text item delimiters to the search_string
set the item_list to every text item of this_text
set AppleScript's text item delimiters to the replacement_string
set this_text to the item_list as string
set AppleScript's text item delimiters to ""
return this_text
end replace_chars

tell application "iTunes"

set trackArray to tracks of current playlist

set lastAlbum to null
repeat with aTrack in trackArray
set currentAlbum to album of aTrack as string
if currentAlbum is not lastAlbum then
if exists every artwork of aTrack then
set srcBytes to raw data of artwork 1 of aTrack
if format of artwork 1 of aTrack is «class PNG » then
set ext to ".png"
else
set ext to ".jpg"
end if

set str to my replace_chars(currentAlbum, ":", "-")

set fileName to (((path to desktop) as text) & str & ext)

-- write to file
set outFile to open for access file fileName with write permission
-- truncate the file
set eof outFile to 0
-- write the image bytes to the file
write srcBytes to outFile
close access outFile
end if
end if
set lastAlbum to currentAlbum
end repeat
end tell