Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

カテゴリー: Image

CoreImageでフィルタしまくり

Posted on 2月 9, 2018 by Takaaki Naganoya

フィルタ名称をテキストで与えて動的に画像のフィルタ処理を変更させるAppleScriptです。

ただし、各CIFilterのパラメータまでは指定していないため、パラメータ値はデフォルトのままです。別途、パラメータ値を与えるようにすると有用性が増すことでしょう。

多数のCIFilterの名称をリスト(配列)で間接指定して、順次フィルター処理を行なってファイル出力する、というのが本プログラムの実験内容です。


▲Original


▲Filtered Image

AppleScript名:CoreImageでフィルタしまくり
— Created 2014-12-09 by Takaaki Naganoya
— 2014 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "QuartzCore"

property CIFilter : a reference to current application’s CIFilter
property |NSURL| : a reference to current application’s |NSURL|
property CIImage : a reference to current application’s CIImage
property NSJPEGFileType : a reference to current application’s NSJPEGFileType
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep

–CIFilters (Not everything!!) From Apple’s Core Image Filter Reference
set ciList to {"CIColorPosterize"} –{"CIColorInvert", "CIBoxBlur", "CIDiscBlur", "CIGaussianBlur", "CIMedianFilter", "CIMotionBlur", "CINoiseReduction", "CIZoomBlur", "CIColorMonochrome", "CIColorPosterize", "CIPhotoEffectChrome", "CISepiaTone", "CISharpenLuminance", "CIUnsharpMask", "CIKaleidoscope"}

–画像を選択
set aPath to POSIX path of (choose file of type {"public.image"})

–すべてのフィルタを実行
repeat with i in ciList
  set j to contents of i
  
set aRes to convAsFilteredJPEG(aPath, j) of me
end repeat

–CIFilterをかけたJPEG画像を生成
–参照:http://ashplanning.blogspot.jp/ のうちのどこか
on convAsFilteredJPEG(aPath, aFilterName)
  set aURL to (|NSURL|’s fileURLWithPath:aPath) –Input
  
set aPOSIX to (POSIX path of aPath) & "_" & aFilterName & ".jpg" –Output
  
  
–CIImageを生成
  
set aCIImage to CIImage’s alloc()’s initWithContentsOfURL:aURL
  
  
— CIFilter をフィルタの名前で生成
  
set aFilter to CIFilter’s filterWithName:aFilterName
  
aFilter’s setDefaults() –各フィルタのパラメータはデフォルト(そこが問題)
  
  
–Filterを実行
  
aFilter’s setValue:aCIImage forKey:"inputImage"
  
set aOutImage to aFilter’s valueForKey:"outputImage"
  
  
— NSBitmapImageRep を CIImage から生成
  
set aRep to NSBitmapImageRep’s alloc()’s initWithCIImage:aOutImage
  
  
— NSBitmapImageRep から JPEG データを取得
  
set jpegData to aRep’s representationUsingType:(NSJPEGFileType) |properties|:(missing value)
  
  
— ファイルに保存
  
return (jpegData’s writeToFile:aPOSIX atomically:true) as boolean
end convAsFilteredJPEG

★Click Here to Open This Script 

Posted in file filter Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

CoreImageで指定画像をCIGaussianBlur

Posted on 2月 9, 2018 by Takaaki Naganoya


▲Original


▲Filtered Image

AppleScript名:CoreImageで指定画像をCIGaussianBlur
— Created 2017-03-21 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "QuartzCore"

–画像を選択
set aPath to POSIX path of (choose file of type {"public.image"})
set aNSImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:aPath

set paramRec to {inputRadius:10.0}
set imgRes to execCIFilterWithNSImageAndParams(aNSImage, "CIGaussianBlur", paramRec) of me

set aDesktopPath to (current application’s NSProcessInfo’s processInfo()’s environment()’s objectForKey:("HOME"))’s stringByAppendingString:"/Desktop/"
set savePath to aDesktopPath’s stringByAppendingString:((current application’s NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png")

set fRes to saveNSImageAtPathAsPNG(imgRes, savePath) of me

–NSImageをCIImageに変換してCIfilterを実行
on execCIFilterWithNSImageAndParams(aNSImage, aFilterName as string, paramRec as record)
  set aDict to current application’s NSDictionary’s dictionaryWithDictionary:paramRec
  
  
set aCIImage to convNSImageToCIimage(aNSImage) of me
  
set aFilter to current application’s CIFilter’s filterWithName:aFilterName
  
  
aFilter’s setDefaults()
  
aFilter’s setValue:aCIImage forKey:"inputImage"
  
set aOutImage to aFilter’s valueForKey:"outputImage"
  
  
set keyList to aDict’s allKeys() as list
  
repeat with i in keyList
    set aVal to (aDict’s valueForKey:i) as list of string or string –as anything
    (
aFilter’s setValue:aVal forKey:(i as string))
  end repeat
  
  
set newNSImage to convCIimageToNSImage(aOutImage) of me
  
return newNSImage
end execCIFilterWithNSImageAndParams

on convCIimageToNSImage(aCIImage)
  set aRep to current application’s NSBitmapImageRep’s alloc()’s initWithCIImage:aCIImage
  
set tmpSize to aRep’s |size|()
  
set newImg to current application’s NSImage’s alloc()’s initWithSize:tmpSize
  
newImg’s addRepresentation:aRep
  
return newImg
end convCIimageToNSImage

on convNSImageToCIimage(aNSImage)
  set tiffDat to aNSImage’s TIFFRepresentation()
  
set aRep to current application’s NSBitmapImageRep’s imageRepWithData:tiffDat
  
set newImg to current application’s CIImage’s alloc()’s initWithBitmapImageRep:aRep
  
return newImg
end convNSImageToCIimage

–NSImageを指定パスにPNG形式で保存
on saveNSImageAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –成功ならtrue、失敗ならfalseが返る
end saveNSImageAtPathAsPNG

★Click Here to Open This Script 

Posted in file filter Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

CoreImageで指定画像をCIDiscBlur

Posted on 2月 9, 2018 by Takaaki Naganoya


▲Original


▲Filtered Image

AppleScript名:CoreImageで指定画像をCIDiscBlur
— Created 2017-03-21 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "QuartzCore"

–画像を選択
set aPath to POSIX path of (choose file of type {"public.image"})
set aNSImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:aPath

set paramRec to {inputRadius:10.0}
set imgRes to execCIFilterWithNSImageAndParams(aNSImage, "CIDiscBlur", paramRec) of me

set aDesktopPath to (current application’s NSProcessInfo’s processInfo()’s environment()’s objectForKey:("HOME"))’s stringByAppendingString:"/Desktop/"
set savePath to aDesktopPath’s stringByAppendingString:((current application’s NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png")

set fRes to saveNSImageAtPathAsPNG(imgRes, savePath) of me

–NSImageをCIImageに変換してCIfilterを実行
on execCIFilterWithNSImageAndParams(aNSImage, aFilterName as string, paramRec as record)
  set aDict to current application’s NSDictionary’s dictionaryWithDictionary:paramRec
  
  
set aCIImage to convNSImageToCIimage(aNSImage) of me
  
set aFilter to current application’s CIFilter’s filterWithName:aFilterName
  
  
aFilter’s setDefaults()
  
aFilter’s setValue:aCIImage forKey:"inputImage"
  
set aOutImage to aFilter’s valueForKey:"outputImage"
  
  
set keyList to aDict’s allKeys() as list
  
repeat with i in keyList
    set aVal to (aDict’s valueForKey:i) as list of string or string –as anything
    (
aFilter’s setValue:aVal forKey:(i as string))
  end repeat
  
  
set newNSImage to convCIimageToNSImage(aOutImage) of me
  
return newNSImage
end execCIFilterWithNSImageAndParams

on convCIimageToNSImage(aCIImage)
  set aRep to current application’s NSBitmapImageRep’s alloc()’s initWithCIImage:aCIImage
  
set tmpSize to aRep’s |size|()
  
set newImg to current application’s NSImage’s alloc()’s initWithSize:tmpSize
  
newImg’s addRepresentation:aRep
  
return newImg
end convCIimageToNSImage

on convNSImageToCIimage(aNSImage)
  set tiffDat to aNSImage’s TIFFRepresentation()
  
set aRep to current application’s NSBitmapImageRep’s imageRepWithData:tiffDat
  
set newImg to current application’s CIImage’s alloc()’s initWithBitmapImageRep:aRep
  
return newImg
end convNSImageToCIimage

–NSImageを指定パスにPNG形式で保存
on saveNSImageAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –成功ならtrue、失敗ならfalseが返る
end saveNSImageAtPathAsPNG

★Click Here to Open This Script 

Posted in file filter Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

CoreImageで指定画像をCIColorMonochrome

Posted on 2月 9, 2018 by Takaaki Naganoya


▲Original


▲Filtered Image

AppleScript名:CoreImageで指定画像をCIColorMonochrome
— Created 2017-03-21 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "QuartzCore"
use framework "AppKit"

property CIFilter : a reference to current application’s CIFilter
property CIColor : a reference to current application’s CIColor
property NSUUID : a reference to current application’s NSUUID
property CIImage : a reference to current application’s CIImage
property NSColor : a reference to current application’s NSColor
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property NSDictionary : a reference to current application’s NSDictionary
property NSProcessInfo : a reference to current application’s NSProcessInfo
property NSPNGFileType : a reference to current application’s NSPNGFileType
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep

–画像を選択
set aPath to POSIX path of (choose file of type {"public.image"})
set aNSImage to NSImage’s alloc()’s initWithContentsOfFile:aPath

set aCIColor to makeCIColorFromParams(0.0, 1.0, 0.0, 1.0) of me

set paramRec to {inputColor:aCIColor, inputIntensity:1.0}
set imgRes to execCIFilterWithNSImageAndParams(aNSImage, "CIColorMonochrome", paramRec) of me

set aDesktopPath to (NSProcessInfo’s processInfo()’s environment()’s objectForKey:("HOME"))’s stringByAppendingString:"/Desktop/"
set savePath to aDesktopPath’s stringByAppendingString:((NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png")

set fRes to saveNSImageAtPathAsPNG(imgRes, savePath) of me

–NSImageをCIImageに変換してCIfilterを実行
on execCIFilterWithNSImageAndParams(aNSImage, aFilterName as string, paramRec as record)
  set aDict to NSDictionary’s dictionaryWithDictionary:paramRec
  
  
set aCIImage to convNSImageToCIimage(aNSImage) of me
  
set aFilter to CIFilter’s filterWithName:aFilterName
  
  
aFilter’s setDefaults()
  
aFilter’s setValue:aCIImage forKey:"inputImage"
  
set aOutImage to aFilter’s valueForKey:"outputImage"
  
  
set keyList to aDict’s allKeys() as list
  
repeat with i in keyList
    set aVal to (aDict’s valueForKey:i) as list of string or string –as anything
    (
aFilter’s setValue:aVal forKey:(i as string))
  end repeat
  
  
set newNSImage to convCIimageToNSImage(aOutImage) of me
  
return newNSImage
end execCIFilterWithNSImageAndParams

on makeCIColorFromParams(redValue, greenValue, blueValue, alphaValue)
  set aNSColor to NSColor’s colorWithCalibratedRed:redValue green:greenValue blue:blueValue alpha:alphaValue
  
set aCIColor to CIColor’s alloc()’s initWithColor:aNSColor
  
return aCIColor
end makeCIColorFromParams

on convCIimageToNSImage(aCIImage)
  set aRep to NSBitmapImageRep’s alloc()’s initWithCIImage:aCIImage
  
set tmpSize to aRep’s |size|()
  
set newImg to NSImage’s alloc()’s initWithSize:tmpSize
  
newImg’s addRepresentation:aRep
  
return newImg
end convCIimageToNSImage

on convNSImageToCIimage(aNSImage)
  set tiffDat to aNSImage’s TIFFRepresentation()
  
set aRep to NSBitmapImageRep’s imageRepWithData:tiffDat
  
set newImg to CIImage’s alloc()’s initWithBitmapImageRep:aRep
  
return newImg
end convNSImageToCIimage

–NSImageを指定パスにPNG形式で保存
on saveNSImageAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(NSPNGFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –成功ならtrue、失敗ならfalseが返る
end saveNSImageAtPathAsPNG

★Click Here to Open This Script 

Posted in file filter Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

CoreImageで指定画像をBoxBlur v2

Posted on 2月 9, 2018 by Takaaki Naganoya


▲Original


▲Filtered Image

AppleScript名:CoreImageで指定画像をBoxBlur v2
— Created 2017-03-21 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "QuartzCore"

property CIFilter : a reference to current application’s CIFilter
property |NSURL| : a reference to current application’s |NSURL|
property NSUUID : a reference to current application’s NSUUID
property CIImage : a reference to current application’s CIImage
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property NSProcessInfo : a reference to current application’s NSProcessInfo
property NSPNGFileType : a reference to current application’s NSPNGFileType
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep

–画像を選択
set aPath to POSIX path of (choose file of type {"public.image"})
set aNSImage to NSImage’s alloc()’s initWithContentsOfFile:aPath

set paramRec to {inputRadius:10} –5から10
set imgRes to execCIFilterWithNSImageAndParams(aNSImage, "CIBoxBlur", paramRec) of me

set savePath to retUUIDfilePath(aPath, "png") of me
set fRes to saveNSImageAtPathAsPNG(imgRes, savePath) of me

–NSImageをCIImageに変換してCIfilterを実行
on execCIFilterWithNSImageAndParams(aNSImage, aFilterName as string, paramRec as record)
  set aDict to current application’s NSDictionary’s dictionaryWithDictionary:paramRec
  
  
set aCIImage to convNSImageToCIimage(aNSImage) of me
  
set aFilter to current application’s CIFilter’s filterWithName:aFilterName
  
  
aFilter’s setDefaults()
  
aFilter’s setValue:aCIImage forKey:"inputImage"
  
set aOutImage to aFilter’s valueForKey:"outputImage"
  
  
set keyList to aDict’s allKeys() as list
  
repeat with i in keyList
    set aVal to (aDict’s valueForKey:i) as list of string or string –as anything
    (
aFilter’s setValue:aVal forKey:(i as string))
  end repeat
  
  
set newNSImage to convCIimageToNSImage(aOutImage) of me
  
return newNSImage
end execCIFilterWithNSImageAndParams

on convCIimageToNSImage(aCIImage)
  set aRep to NSBitmapImageRep’s alloc()’s initWithCIImage:aCIImage
  
set tmpSize to aRep’s |size|()
  
set newImg to NSImage’s alloc()’s initWithSize:tmpSize
  
newImg’s addRepresentation:aRep
  
return newImg
end convCIimageToNSImage

on convNSImageToCIimage(aNSImage)
  set tiffDat to aNSImage’s TIFFRepresentation()
  
set aRep to NSBitmapImageRep’s imageRepWithData:tiffDat
  
set newImg to CIImage’s alloc()’s initWithBitmapImageRep:aRep
  
return newImg
end convNSImageToCIimage

on retUUIDfilePath(aPath, aEXT)
  set aUUIDstr to (NSUUID’s UUID()’s UUIDString()) as string
  
set aPath to ((NSString’s stringWithString:aPath)’s stringByDeletingLastPathComponent()’s stringByAppendingPathComponent:aUUIDstr)’s stringByAppendingPathExtension:aEXT
  
return aPath
end retUUIDfilePath

–NSImageを指定パスにPNG形式で保存
on saveNSImageAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(NSPNGFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –true/false
end saveNSImageAtPathAsPNG

★Click Here to Open This Script 

Posted in file filter Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

CoreImageで指定画像を2階調ポスタライズ v2

Posted on 2月 9, 2018 by Takaaki Naganoya


▲Original


▲2-level postalized image

AppleScript名:CoreImageで指定画像を2階調ポスタライズ v2
— Created 2014-12-09 by Takaaki Naganoya
— 2014 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "QuartzCore"

property |NSURL| : a reference to current application’s |NSURL|
property NSUUID : a reference to current application’s NSUUID
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property NSPNGFileType : a reference to current application’s NSPNGFileType
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep

–CIFilters (Not everything!!) From Apple’s Core Image Filter Reference
set cifilterName to "CIColorPosterize"

–画像を選択
set aPath to POSIX path of (choose file of type {"public.image"})

–指定フィルタ名でフィルタしたNSImageを取得
set nsimageRes to filterAnImageFile(aPath, cifilterName) of me

–Save as PNG
set fRes to retUUIDfilePath(aPath, "png") of me
set sRes to saveNSImageAtPathAsPNG(nsimageRes, fRes) of me

–CIFilterをかけたJPEG画像を生成
–参照:http://ashplanning.blogspot.jp/ のうちのどこか
on filterAnImageFile(aPath, aFilterName)
  –CIImageを生成
  
set aURL to current application’s |NSURL|’s fileURLWithPath:aPath –Input
  
set aCIImage to current application’s CIImage’s alloc()’s initWithContentsOfURL:aURL
  
  
— CIFilter をフィルタの名前で生成
  
set aFilter to current application’s CIFilter’s filterWithName:aFilterName
  
aFilter’s setDefaults() –各フィルタのパラメータはデフォルト
  
  
–Filterを実行
  
aFilter’s setValue:aCIImage forKey:"inputImage"
  
aFilter’s setValue:2 forKey:"inputLevels"
  
  
set aOutImage to aFilter’s valueForKey:"outputImage"
  
set outNSImage to convCIimageToNSImage(aOutImage) of me
  
return outNSImage
end filterAnImageFile

on convCIimageToNSImage(aCIImage)
  set aRep to current application’s NSBitmapImageRep’s alloc()’s initWithCIImage:aCIImage
  
set tmpSize to aRep’s |size|()
  
set newImg to current application’s NSImage’s alloc()’s initWithSize:tmpSize
  
newImg’s addRepresentation:aRep
  
return newImg
end convCIimageToNSImage

on convNSImageToCIimage(aNSImage)
  set tiffDat to aNSImage’s TIFFRepresentation()
  
set aRep to current application’s NSBitmapImageRep’s imageRepWithData:tiffDat
  
set newImg to current application’s CIImage’s alloc()’s initWithBitmapImageRep:aRep
  
return newImg
end convNSImageToCIimage

on retUUIDfilePath(aPath, aEXT)
  set aUUIDstr to (NSUUID’s UUID()’s UUIDString()) as string
  
set aPath to ((NSString’s stringWithString:aPath)’s stringByDeletingLastPathComponent()’s stringByAppendingPathComponent:aUUIDstr)’s stringByAppendingPathExtension:aEXT
  
return aPath
end retUUIDfilePath

–NSImageを指定パスにPNG形式で保存
on saveNSImageAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(NSPNGFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –true/false
end saveNSImageAtPathAsPNG

★Click Here to Open This Script 

Posted in file filter Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定画像をBMP形式で保存

Posted on 2月 9, 2018 by Takaaki Naganoya
AppleScript名:指定画像をBMP形式で保存
— Created 2017-02-05 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set aFile to POSIX path of (choose file of type {"public.image"} with prompt "Select Image A")
set aImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:aFile

set fRes to retUUIDfilePath(aFile, "bmp") of me
set sRes to saveNSImageAtPathAsBMP(imgRes, fRes) of me

on retUUIDfilePath(aPath, aEXT)
  set aUUIDstr to (current application’s NSUUID’s UUID()’s UUIDString()) as string
  
set aPath to ((current application’s NSString’s stringWithString:aPath)’s stringByDeletingLastPathComponent()’s stringByAppendingPathComponent:aUUIDstr)’s stringByAppendingPathExtension:aEXT
  
return aPath
end retUUIDfilePath

–NSImageを指定パスにBMP形式で保存
on saveNSImageAtPathAsBMP(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSBMPFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –true/false
end saveNSImageAtPathAsBMP

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定画像をPNG形式で保存

Posted on 2月 9, 2018 by Takaaki Naganoya
AppleScript名:指定画像をPNG形式で保存
— Created 2017-02-05 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set aFile to POSIX path of (choose file of type {"public.image"} with prompt "Select Image A")
set aImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:aFile

set fRes to retUUIDfilePath(aFile, "png") of me
set sRes to saveNSImageAtPathAsPNG(imgRes, fRes) of me

on retUUIDfilePath(aPath, aEXT)
  set aUUIDstr to (current application’s NSUUID’s UUID()’s UUIDString()) as string
  
set aPath to ((current application’s NSString’s stringWithString:aPath)’s stringByDeletingLastPathComponent()’s stringByAppendingPathComponent:aUUIDstr)’s stringByAppendingPathExtension:aEXT
  
return aPath
end retUUIDfilePath

–NSImageを指定パスにPNG形式で保存
on saveNSImageAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –true/false
end saveNSImageAtPathAsPNG

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定画像をJPG形式で保存

Posted on 2月 9, 2018 by Takaaki Naganoya

指定の画像をJPEG形式+指定圧縮率で保存するAppleScriptです。

現在は、これをさらに発展させて指定ファイルサイズになるまで圧縮率を順次変更して動的に圧縮率を変更して保存する、という処理に発展し、これは日常的に(SNSなどでアップロード可能なファイルサイズに制限があるサイトに画像掲載を行うさいに)利用しています。

AppleScript名:指定画像をJPG形式で保存
— Created 2017-02-05 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set aFile to POSIX path of (choose file of type {"public.image"} with prompt "Select Image A")
set aImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:aFile

set fRes to retUUIDfilePath(aFile, "jpg") of me
set sRes to saveNSImageAtPathAsJPG(aImage, fRes, 1.0) of me

on retUUIDfilePath(aPath, aEXT)
  set aUUIDstr to (current application’s NSUUID’s UUID()’s UUIDString()) as string
  
set aPath to ((current application’s NSString’s stringWithString:aPath)’s stringByDeletingLastPathComponent()’s stringByAppendingPathComponent:aUUIDstr)’s stringByAppendingPathExtension:aEXT
  
return aPath
end retUUIDfilePath

–NSImageを指定パスにJPEG形式で保存、qulityNumは0.0〜1.0。1.0は無圧縮
on saveNSImageAtPathAsJPG(anImage, outPath, qulityNum as real)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSJPEGFileType) |properties|:{NSImageCompressionFactor:qulityNum})
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –true/false
end saveNSImageAtPathAsJPG

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定画像をTIFF形式で保存

Posted on 2月 9, 2018 by Takaaki Naganoya
AppleScript名:指定画像をTIFF形式で保存
— Created 2017-02-05 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set aFile to POSIX path of (choose file of type {"public.image"} with prompt "Select Image A")
set aImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:aFile

set fRes to retUUIDfilePath(aFile, "tif") of me
set sRes to saveNSImageAtPathAsTIFF(imgRes, fRes) of me

on retUUIDfilePath(aPath, aEXT)
  set aUUIDstr to (current application’s NSUUID’s UUID()’s UUIDString()) as string
  
set aPath to ((current application’s NSString’s stringWithString:aPath)’s stringByDeletingLastPathComponent()’s stringByAppendingPathComponent:aUUIDstr)’s stringByAppendingPathExtension:aEXT
  
return aPath
end retUUIDfilePath

–NSImageを指定パスにTIFF形式で保存
on saveNSImageAtPathAsTIFF(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSTIFFFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –true/false
end saveNSImageAtPathAsTIFF

★Click Here to Open This Script 

Posted in file Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

画像にステガノグラフィーで埋め込まれた文字列を取り出す

Posted on 2月 9, 2018 by Takaaki Naganoya

オープンソースのステガノグラフィーのプログラム「ISStego」(By Isaac Stevao Sena氏)を用いて、JPEG画像に埋め込んだ文字情報を取り出すAppleScriptです。

ISStegoは普通にObjective-Cで書かれたGUIベースのアプリケーションだったので、そのままではAppleScriptから呼び出せませんでした。

そこで、中身をそのままそっくり移し替えた新規フレームワーク「stegLib.framework」をでっちあげてビルドし、AppleScriptから呼び出してみました。

JPEG画像にUTF-8の文字情報(日本語文字列)を埋め込んで別のPNG画像に書き出し、書き出した画像からUTF-8の文字情報を取り出す実験を行ってみました。エンコードもデコードもうまく行っているようなので、うまく処理できていると思います。

ステガノグラフィーについて初めて聞いたのは20年ぐらい前のことと記憶していますが、こんなに手軽に使えるようになっていたとは驚きです。


▲Original Image


▲Information Embedded Image

–> stegLib.framework

AppleScript名:画像にステガノグラフィーで埋め込まれた文字列を取り出す
— Created 2015-10-21 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "stegLib" –https://github.com/isena/ISStego

set aFile to POSIX path of (choose file of type {"public.png"})
set aFilePath to current application’s NSString’s stringWithString:aFile
set aURL to current application’s |NSURL|’s fileURLWithPath:aFilePath
set aImage to current application’s NSImage’s alloc()’s initWithContentsOfURL:aURL

set aDecodedData to current application’s ISStegoDecoder’s alloc()’s init()’s decodeStegoImage:aImage |error|:(missing value)
set resStr to (current application’s NSString’s alloc()’s initWithData:aDecodedData encoding:(current application’s NSUTF8StringEncoding)) as string
–> "長野谷隆昌/ぴよまるソフトウェア/Piyomaru Software"

★Click Here to Open This Script 

Posted in file Image Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

画像にステガノグラフィーで情報を埋め込む

Posted on 2月 9, 2018 by Takaaki Naganoya

オープンソースのステガノグラフィー(steganography)のプログラム「ISStego」(By Isaac Stevao Sena氏)を用いて、JPEG画像に文字情報を埋め込むAppleScriptです。

ISStegoは普通にObjective-Cで書かれたGUIベースのアプリケーションだったので、そのままではAppleScriptから呼び出せませんでした。

そこで、中身をそのままそっくり移し替えた新規フレームワーク「stegLib.framework」をでっちあげてビルドし、AppleScriptから呼び出してみました。

JPEG画像にUTF-8の文字情報(日本語文字列)を埋め込んで別のPNG画像に書き出し、書き出した画像からUTF-8の文字情報を取り出す実験を行ってみました。エンコードもデコードもうまく行っているようなので、うまく処理できていると思います。

ステガノグラフィー(steganography)について初めて聞いたのは20年ぐらい前のことと記憶していますが、こんなに手軽に使えるようになっていたとは驚きです。

Twitterにプログラムを投稿するのに、(140文字制限を回避するため)文字を画像化して投稿しているのを見て、「そこまでやるなら、画像にプログラムの文字データを埋め込めばいいのに」と思い、「ステガノグラフィーで埋め込めばいいんじゃないか?」ということで、埋め込めるようになったのですが、肝心のTwitterクライアントから画像をダウンロードする手段がなかったのがダメダメでした(Webブラウザ経由ならOKです)。


▲Original Image


▲Information Embedded Image

–> stegLib.framework

AppleScript名:画像にステガノグラフィーで情報を埋め込む
— Created 2015-10-21 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "stegLib" –https://github.com/isena/ISStego

set aFile to POSIX path of (choose file of type {"public.jpeg"})
set encString to "長野谷隆昌/ぴよまるソフトウェア/Piyomaru Software"

set aFilePath to current application’s NSString’s stringWithString:aFile
set aExt to "png"

set newPath to aFilePath’s stringByDeletingPathExtension()
set newPath2 to newPath’s stringByAppendingString:"_stego"
set newPath3 to newPath2’s stringByAppendingPathExtension:aExt

set aURL to current application’s |NSURL|’s fileURLWithPath:aFilePath
set aImage to current application’s NSImage’s alloc()’s initWithContentsOfURL:aURL
set strData to current application’s NSString’s stringWithString:encString

set aEncimage to current application’s ISStegoEncoder’s alloc()’s init()’s stegoImageForImage:aImage |data|:strData |error|:(missing value)
my saveImageRepAtPathAsPNG(aEncimage, newPath3)

–画像を指定パスにPNG形式で保存
on saveImageRepAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep
  
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value))
  
return (myNewImageData’s writeToFile:newPath atomically:true) as boolean
end saveImageRepAtPathAsPNG

★Click Here to Open This Script 

Posted in file Image Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定写真をQRコード認識してエンコードされたデータをデコード

Posted on 2月 8, 2018 by Takaaki Naganoya

–> {“MEMORY:(メモ文字列)
NAME1:(姓名)
NAME2:(姓名読み)
TEL1:(電話番号1)
MAIL1:(メールアドレス1)
TEL2:(電話番号2)
MAIL2:(メールアドレス2)
MECARD:N:(姓),(名);SOUND:(姓読み),(名読み);TEL:(電話番号1);TEL:(電話番号2);EMAIL:(メールアドレス1);EMAIL:(メールアドレス2);NOTE:(メモ文字列) ;;”}

AppleScript名:指定写真をQRコード認識してエンコードされたデータをデコード
use AppleScript version "2.4"
use framework "Foundation"
use framework "QuartzCore"
use scripting additions

–画像選択
set inputFile to choose file of type {"public.image"}

–QRコード検出
set recogRes to qrcodeDetect(inputFile) of me

–>
(*
{"http://www.su-gomori.com \nMEBKM:TITLE:スゴモリ;URL:http¥://www.su-gomori.com;;"}
*)

on qrcodeDetect(inputFile)
  –画像オープン
  
set imageRef to openImageFile(inputFile)
  
  
— 検出器のオプションを NSDictonary で作成
  
set optDic1 to current application’s NSDictionary’s dictionaryWithObject:(current application’s CIDetectorAccuracyHigh) forKey:(current application’s CIDetectorAccuracy)
  
set faceDetector to current application’s CIDetector’s detectorOfType:(current application’s CIDetectorTypeQRCode) context:(missing value) options:optDic1
  
  
— QRコードの検出を行う際のオプションを NSDictonary で作成
  
set optDic2 to current application’s NSDictionary’s dictionaryWithObject:(current application’s CIDetectorImageOrientation) forKey:"Orientation"
  
  
— QRコード検出を実行
  
set faceArray to faceDetector’s featuresInImage:imageRef options:optDic2
  
set fList to {}
  
  
— 検出されたQRコードの位置とサイズをログに出力
  
repeat with i from 1 to (count of faceArray)
    set face to item i of faceArray
    
set bRec to (face’s messageString()) as string
    
–set cRec to retURLdecodedStrings(bRec) of me –URLエンコード対策
    
set the end of fList to bRec
  end repeat
  
  
return fList
  
end qrcodeDetect

on openImageFile(imageFile) — imageFile: POSIX path 形式のファイルパス
  — aliasをURLに変換
  
set fileURL to current application’s |NSURL|’s fileURLWithPath:(POSIX path of imageFile)
  
— CIImage を生成
  
return current application’s CIImage’s alloc()’s initWithContentsOfURL:fileURL
end openImageFile

on retURLencodedStrings(aText)
  set aStr to current application’s NSString’s stringWithString:aText
  
set encodedStr to aStr’s stringByAddingPercentEncodingWithAllowedCharacters:(current application’s NSCharacterSet’s alphanumericCharacterSet())
  
return encodedStr as text
end retURLencodedStrings

on retURLdecodedStrings(aURLencodedStr)
  set aStr to current application’s NSString’s stringWithString:aURLencodedStr
  
set aDecoded to aStr’s stringByRemovingPercentEncoding()
  
return aDecoded as text
end retURLdecodedStrings

★Click Here to Open This Script 

Posted in Image | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

指定文字列からQRコード画像(PNG)をデスクトップに作成する(日本語を含むデータ)v2_画像拡大倍率指定

Posted on 2月 8, 2018 by Takaaki Naganoya

AppleScript名:指定文字列からQRコード画像(PNG)をデスクトップに作成する(日本語を含むデータ)v2_画像拡大倍率指定
— Created 2016-03-16 by Takaaki Naganoya
— Modified 2017-01-15 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "QuartzCore"

–QRCodeを作成
set a to "MEMORY:(メモ文字列)
NAME1:(姓名)
NAME2:(姓名読み)
TEL1:(電話番号1)
MAIL1:(メールアドレス1)
TEL2:(電話番号2)
MAIL2:(メールアドレス2)
MECARD:N:(姓),(名);SOUND:(姓読み),(名読み);TEL:(電話番号1);TEL:(電話番号2);EMAIL:(メールアドレス1);EMAIL:(メールアドレス2);NOTE:(メモ文字列) ;;"

set aStr to current application’s NSString’s stringWithString:a
set strData to aStr’s dataUsingEncoding:(current application’s NSShiftJISStringEncoding) –シフトJISにエンコード
set qrFilter to current application’s CIFilter’s filterWithName:"CIQRCodeGenerator"
qrFilter’s setValue:strData forKey:"inputMessage"
qrFilter’s setValue:"H" forKey:"inputCorrectionLevel"
set anImage to qrFilter’s outputImage()

set convImg to convCIimageToNSImage(anImage) of me

–NSImageを拡大(アンチエイリアス解除で)
set resizedImg to my resizeNSImageWithoutAntlialias:convImg toScale:16.0

–デスクトップに保存
set aDesktopPath to (current application’s NSProcessInfo’s processInfo()’s environment()’s objectForKey:("HOME"))’s stringByAppendingString:"/Desktop/"
set savePath to aDesktopPath’s stringByAppendingString:((current application’s NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png")
saveNSImageAtPathAsPNG(resizedImg, savePath) of me

on convCIimageToNSImage(aCIImage)
  set aRep to current application’s NSBitmapImageRep’s alloc()’s initWithCIImage:aCIImage
  
set tmpSize to aRep’s |size|()
  
set newImg to current application’s NSImage’s alloc()’s initWithSize:tmpSize
  
newImg’s addRepresentation:aRep
  
return newImg
end convCIimageToNSImage

on convNSImageToCIimage(aNSImage)
  set tiffDat to aNSImage’s TIFFRepresentation()
  
set aRep to current application’s NSBitmapImageRep’s imageRepWithData:tiffDat
  
set newImg to current application’s CIImage’s alloc()’s initWithBitmapImageRep:aRep
  
return newImg
end convNSImageToCIimage

–NSImageを指定パスにPNG形式で保存
on saveNSImageAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –成功ならtrue、失敗ならfalseが返る
end saveNSImageAtPathAsPNG

–NSImageを指定倍率で拡大(アンチエイリアス解除状態で)–By Shane Stanley
on resizeNSImageWithoutAntlialias:aSourceImg toScale:imgScale
  set aSize to aSourceImg’s |size|()
  
set aWidth to (aSize’s width) * imgScale
  
set aHeight to (aSize’s height) * imgScale
  
  
set aRep to current application’s NSBitmapImageRep’s alloc()’s initWithBitmapDataPlanes:(missing value) pixelsWide:aWidth pixelsHigh:aHeight bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(current application’s NSCalibratedRGBColorSpace) bytesPerRow:0 bitsPerPixel:0
  
  
set newSize to {width:aWidth, height:aHeight}
  
aRep’s setSize:newSize
  
  
current application’s NSGraphicsContext’s saveGraphicsState()
  
  
set theContext to current application’s NSGraphicsContext’s graphicsContextWithBitmapImageRep:aRep
  
current application’s NSGraphicsContext’s setCurrentContext:theContext
  
theContext’s setShouldAntialias:false
  
theContext’s setImageInterpolation:(current application’s NSImageInterpolationNone)
  
  
aSourceImg’s drawInRect:(current application’s NSMakeRect(0, 0, aWidth, aHeight)) fromRect:(current application’s NSZeroRect) operation:(current application’s NSCompositeCopy) fraction:(1.0)
  
  
current application’s NSGraphicsContext’s restoreGraphicsState()
  
  
set newImg to current application’s NSImage’s alloc()’s initWithSize:newSize
  
newImg’s addRepresentation:aRep
  
  
return newImg
end resizeNSImageWithoutAntlialias:toScale:

★Click Here to Open This Script 

Posted in Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Finder上で選択中の画像を横方向に連結

Posted on 2月 8, 2018 by Takaaki Naganoya

–> MagicKit.framework

AppleScript名:Finder上で選択中の画像を横方向に連結
— Created 2017-11-21 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "QuartzCore"
use framework "AppKit"
use framework "MagicKit" –https://github.com/aidansteele/magickit

property |NSURL| : a reference to current application’s |NSURL|
property NSUUID : a reference to current application’s NSUUID
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property GEMagicKit : a reference to current application’s GEMagicKit
property NSPNGFileType : a reference to current application’s NSPNGFileType
property NSMutableArray : a reference to current application’s NSMutableArray
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep

property xGap : 10 –連結時の画像間のアキ(横方向)

tell application "Finder"
  set aSel to selection as alias list
  
if aSel = {} or aSel = "" then return
end tell

–選択した画像をArrayに入れる
set imgList to NSMutableArray’s new()
repeat with i in aSel
  set aPath to POSIX path of i
  
  
–指定ファイルのUTIを取得して、画像(public.image)があれば処理を行う
  
set aRes to (GEMagicKit’s magicForFileAtPath:aPath)
  
set utiList to (aRes’s uniformTypeHierarchy()) as list
  
if "public.image" is in utiList then
    set aNSImage to (NSImage’s alloc()’s initWithContentsOfFile:aPath)
    (
imgList’s addObject:aNSImage)
  end if
end repeat

–KVCで画像の各種情報をまとめて取得
set sizeList to (imgList’s valueForKeyPath:"size") as list –NSSize to list of record conversion
set maxHeight to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@max.height") as real
set totalWidth to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@sum.width") as real
set totalCount to ((NSArray’s arrayWithArray:sizeList)’s valueForKeyPath:"@count") as integer

–出力画像作成
set tSize to current application’s NSMakeSize((totalWidth + (xGap * totalCount)), maxHeight)
set newImage to NSImage’s alloc()’s initWithSize:tSize

–順次画像を新規画像に上書き
set xOrig to 0
repeat with i in (imgList as list)
  set j to contents of i
  
set curSize to j’s |size|()
  
set aRect to {xOrig, (maxHeight – (curSize’s height())), (curSize’s width()), (curSize’s height())}
  
set newImage to composeImage(newImage, j, aRect) of me
  
set xOrig to (curSize’s width()) + xGap
end repeat

–デスクトップにPNG形式でNSImageをファイル保存
set aDesktopPath to current application’s NSHomeDirectory()’s stringByAppendingString:"/Desktop/"
set savePath to aDesktopPath’s stringByAppendingString:((NSUUID’s UUID()’s UUIDString())’s stringByAppendingString:".png")
set fRes to saveNSImageAtPathAsPNG(newImage, savePath) of me

–2つのNSImageを重ね合わせ合成してNSImageで返す
on composeImage(backImage, composeImage, aTargerRect)
  set newImage to NSImage’s alloc()’s initWithSize:(backImage’s |size|())
  
  
copy aTargerRect to {x1, y1, x2, y2}
  
set bRect to current application’s NSMakeRect(x1, y1, x2, y2)
  
  
newImage’s lockFocus()
  
  
set newImageRect to current application’s CGRectZero
  
set newImageRect’s |size| to (newImage’s |size|)
  
  
backImage’s drawInRect:newImageRect
  
composeImage’s drawInRect:bRect
  
  
newImage’s unlockFocus()
  
return newImage
end composeImage

–NSImageを指定パスにPNG形式で保存
on saveNSImageAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(NSPNGFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –成功ならtrue、失敗ならfalseが返る
end saveNSImageAtPathAsPNG

★Click Here to Open This Script 

Posted in Image | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

Dockアイコンにプログレスバーを追加

Posted on 2月 8, 2018 by Takaaki Naganoya

Dockアイコンにプレグレスバーを描画するAppleScriptです。

書き方のクセがあからさまに違うこの内容は、Edama2さんからいただいたものですね、コレ。

–> Demo Movie

AppleScript名:Dockアイコンにプログレスバーを追加
use AppleScript
use framework "Foundation"
use scripting additions

on run
  set max to 100
  
repeat with num from 1 to max
    my progDockTile(max, num)
    
delay 0.1
  end repeat
  
  
#アイコンを元に戻す
  
current application’s NSApp’s setApplicationIconImage:(current application’s NSImage’s imageNamed:"NSApplicationIcon")
end run

#Dockアイコンにプログレスバーを追加
on progDockTile(max, current)
  set appIcon to current application’s NSImage’s imageNamed:"NSApplicationIcon"
  
set iconSize to appIcon’s |size|()
  
  
tell (current application’s NSImage’s alloc()’s initWithSize:iconSize)
    
    
lockFocus()
    
    
appIcon’s dissolveToPoint:(current application’s NSZeroPoint) fraction:1.0
    
set n to (iconSize’s width) / 16
    
    
#プログレスバーの長方形
    
set myRect to current application’s NSMakeRect(n / 2, n, n * 15, n * 1.6) –>{origin:{x:4.0, y:8.0}, |size|:{width:120.0, height:12.800000190735}}
    
    
tell (current application’s NSBezierPath’s ¬
      bezierPathWithRoundedRect:myRect ¬
        xRadius:(myRect’s |size|’s height) / 2 ¬
        
yRadius:(myRect’s |size|’s height) / 2)
      
      
current application’s (NSColor’s colorWithWhite:1.0 alpha:0.4)’s |set|() –>背景色
      
fill()
      
      
current application’s NSColor’s whiteColor()’s |set|() –>枠色
      
stroke()
    end tell
    
    
if current is greater than 0 then
      
      
if current is greater than max then set current to max
      
      
set myRect’s |size|’s width to (myRect’s |size|’s width) / max * current
      
      
tell (current application’s NSBezierPath’s ¬
        bezierPathWithRoundedRect:myRect ¬
          xRadius:(myRect’s |size|’s height) / 2 ¬
          
yRadius:(myRect’s |size|’s height) / 2)
        
        
set strartColor to current application’s NSColor’s colorWithRed:0.15 green:0.55 blue:1 alpha:0.8
        
set endColor to strartColor’s shadowWithLevel:0.7
        
set grad to current application’s NSGradient’s alloc()’s initWithStartingColor:strartColor endingColor:endColor
        
grad’s drawInBezierPath:it angle:270.0
      end tell
    end if
    
    
unlockFocus()
    
    
current application’s NSApp’s setApplicationIconImage:it
  end tell
  
  
return (current + 1)
end progDockTile

★Click Here to Open This Script 

Posted in Icon Image System | Tagged 10.11savvy 10.12savvy 10.13savvy Dock | 1 Comment

アプリケーションのDockアイコンに文字列をバッジ表示(5文字まで)

Posted on 2月 8, 2018 by Takaaki Naganoya

AppleScript名:アプリケーションのDockアイコンに文字列をバッジ表示(5文字まで)
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit" –初版では入っておらず、環境によってはクラッシュした。後から追記

showDockBadge_("")

delay 1

showDockBadge_("77777") –Max 5 文字

delay 5

showDockBadge_("")

–Dockのアプリケーションアイコンに指定文字をバッジ表示
on showDockBadge:theText
  set theDockTile to current application’s NSApp’s dockTile()
  
theDockTile’s setBadgeLabel:theText
  
theDockTile’s display()
end showDockBadge:

★Click Here to Open This Script 

Posted in Icon Image System | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy Dock | Leave a comment

GPUImageで指定画像が真っ白かどうか判定する

Posted on 2月 6, 2018 by Takaaki Naganoya

GPUImage Frameworkを用いて、指定画像が真っ白かどうかを判定するAppleScriptです。

–> GPUImage.framework(To ~/Library/Frameworks/)

指定画像のドットがすべて白いかどうかを判定する処理を真剣に行うと、かなり大変です。

いまでは大したことのない1,024 x 768のサイズの画像であっても、ピクセル数は786,432個。78万ピクセルのデータをRGBの各チャネルについてチェックを行う必要があります。78万×3=240万要素ぐらいの処理を行うわけで、メモリ8Gバイト搭載のMacでAppleScriptを用いて処理するのはつらいものがあります(AppleScriptの配列であるlist型変数はメモリ効率がそれほどよくないので)。

240万要素のList型変数(配列)をループで全要素チェックするだけでもけっこうな時間がかかります。こうした地道なアプローチで攻めるのは物理的に不可能です。実用的ではありません。

すべてのピクセルが白いかチェックするのに実用的な処理といえば、Adobe Photoshopで画像の明度ヒストグラムを求めて、ヒストグラムの配列をチェックするというものがあります(実戦に投入していました)。ただし、処理を行うのにAdobe Photoshopが必要になります。Photoshopがない環境では手も足も出ません。

そこで、GPUImage.frameworkをAppleScriptから呼び出してヒストグラムを計算する方法を見つけました。これであれば、AppleScriptと一緒に配布することも可能ですし、処理もPhotoshopより(起動時間を勘案すると)高速に行えます。

実際に、1024×768および1980×1200の真っ白い画像を作成し、それぞれ1ピクセルだけ黒く塗りつぶして空白検出を行なったところ「空白ではない」ことを検知できました(ただし、1×1の画像の判定をミスするという問題がありました)。

GPUImageのヒストグラム出力は、結果にArrayが返ってくるわけでもなく、ヒストグラム出力「画像」が出てくるだけです。その画像を256ピクセルほどスキャンして検出しています。

指定画像がすべて白いかチェックを行う演算は、PDFの空白ページの検出で利用しています。テキストだけではなく、グラフィック要素が指定ページに存在しているかどうかをチェックするために、GPUImage.frameworkのこのヒストグラム出力機能を利用しています。

GPUImage.framework自体は、Swiftで書き直されたGPUImage2に移行。さらにAppleから OpenGLとOpenGL ESが非推奨になりMetalが推奨になったためにGPUImage2も今度の動向がどうなるか不明。新たなGPUImage3に移行するのか、GPUImage2の機能のまましばらく行くのか動向が気になります(結局、Metal対応のGPUImage3に移行)。

各種の画像フィルター処理については代替手段があるものの、このヒストグラム計算による空白画像検出については現時点で代替手段がないため、調査しておきたいところです。ヒストグラム計算自体はありふれた演算なのですが、Objective-Cでラッピングされている例が少ないので、自分でプログラムを書かないといけないのかもしれません。

→ AppleScriptだけで本Scriptよりも高速に画像の空白判定を行えるようになりました(画像の空白判定 v4)。GPUImage.frameworkの機能はこの種類の処理にはもう使っていません。

AppleScript名:GPUImageで指定画像が真っ白かどうか判定する
— Created 2017-02-12 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "GPUImage"
use framework "Quartz"
use framework "QuartzCore"
use framework "CoreGraphics"

set aFile to POSIX path of (choose file of type {"public.image"} with prompt "Select a image to check which is blank (or not) ")

set aURL to current application’s |NSURL|’s fileURLWithPath:aFile
set anNSImage to current application’s NSImage’s alloc()’s initWithContentsOfURL:aURL

set wRes to my detectAllWhite:anNSImage
–> true (Blank = White)
–> false (Not Blank = Not White)

–指定のNSImageが真っ白かどうかをチェック
on detectAllWhite:anNSImage
  –グレースケールフィルタを通して色要素を削除
  
set grayImage to filterWithNSImage(anNSImage, "GPUImageGrayscaleFilter") of me
  
  
–明度ヒストグラム画像を取得
  
set imgRes to getHistogramFromImage(grayImage, 4) of me
  
  
–画像のサイズ(幅、高さ)をピクセル数で取得する(念のため)
  
set aSize to imgRes’s |size|()
  
set aWidth to aSize’s width()
  
set aHeight to aSize’s height()
  
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:(imgRes’s TIFFRepresentation())
  
  
–白い画像のデータパターン
  
set aWhitePattern to current application’s NSMutableArray’s arrayWithArray:{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0}
  
  
set resArray to current application’s NSMutableArray’s alloc()’s init()
  
repeat with i from 0 to 255
    set origColor to (aRawimg’s colorAtX:i y:1)
    
set srgbColSpace to current application’s NSColorSpace’s genericGrayColorSpace
    
set aColor to (origColor’s colorUsingColorSpace:srgbColSpace)
    
set aWhite to aColor’s whiteComponent()
    (
resArray’s addObject:aWhite)
  end repeat
  
  
set aRes to (resArray’s isEqualTo:aWhitePattern) as boolean
  
return aRes
  
end detectAllWhite:

–各種ヒストグラムの定数(From GPUImage.framework)
–0:kGPUImageHistogramRed
–1:kGPUImageHistogramGreen
–2:kGPUImageHistogramBlue
–3:kGPUImageHistogramRGB
–4:kGPUImageHistogramLuminance

–指定のNSImageを明度ヒストグラム化してNSImageで返す
on getHistogramFromImage(aNSImage, histogramType)
  set aFilter to current application’s GPUImageHistogramFilter’s alloc()’s initWithHistogramType:histogramType
  
set aProcImg to (aFilter’s imageByFilteringImage:aNSImage)
  
return aProcImg
end getHistogramFromImage

–NSImageをGPUImage.frameworkの指定フィルタで処理してNSImageを返す
on filterWithNSImage(aNSImage, filterName as string)
  set aClass to current application’s NSClassFromString(filterName)
  
set aImageFilter to aClass’s alloc()’s init()
  
set aProcImg to (aImageFilter’s imageByFilteringImage:aNSImage)
  
return aProcImg
end filterWithNSImage

★Click Here to Open This Script 

Posted in Image | Tagged 10.11savvy 10.12savvy 10.13savvy | 2 Comments

迷路をRTFで作成して脱出経路を赤く着色する v3

Posted on 2月 6, 2018 by Takaaki Naganoya

–> MazeFinder.framework

AppleScript名:迷路をRTFで作成して脱出経路を赤く着色する v3
— Created 2017-09-19 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "MazeFinder" –https://github.com/tcjennings/MazeFinder

property NSFont : a reference to current application’s NSFont
property NSUUID : a reference to current application’s NSUUID
property NSColor : a reference to current application’s NSColor
property NSString : a reference to current application’s NSString
property Board2D : a reference to current application’s Board2D
property Pathfinder : a reference to current application’s Pathfinder
property NSDictionary : a reference to current application’s NSDictionary
property NSLiteralSearch : a reference to current application’s NSLiteralSearch
property NSMutableArray : a reference to current application’s NSMutableArray
property NSFontAttributeName : a reference to current application’s NSFontAttributeName
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName
property NSDocumentTypeDocumentAttribute : a reference to current application’s NSDocumentTypeDocumentAttribute
–NSNotFoundはプロパティに代入しても認識されなかった

set targFontName to "Courier-Bold" –PostScript Name
set targFontSize to 13 –Point

–迷路テキストデータ作成→Attributed Stringに
set aStr to create2DMazeAndSolveIt(30, 30, 1, 1, 28, 28) of me –Plain Text
set anAttr to changeAttrStrsFontAttribute(aStr, targFontName, targFontSize) of me –Attributed String

–迷路データに着色(参照呼び出し, Call by reference)
markCharOfAttributedString(anAttr, aStr, "!", (NSColor’s redColor())) of me

–結果のRTFをデスクトップ上に書き出す。ファイル名はUUID.rtf
set targFol to current application’s NSHomeDirectory()’s stringByAppendingPathComponent:"Desktop"
set aRes to my saveStyledTextAsRTF(targFol, anAttr)

–指定のAttributed String内で指定文字列が含まれる箇所に指定の色をつける(結果はメイン側に参照渡し)
on markCharOfAttributedString(anAttr, origStr, aTargStr, aColor)
  set rList to searchWordWithRange(origStr, aTargStr) of me
  
repeat with ii in rList
    (anAttr’s addAttribute:(NSForegroundColorAttributeName) value:aColor range:ii)
  end repeat
end markCharOfAttributedString

–指定の文字列をAttributed Stringに変換して任意のフォントを一括指定
on changeAttrStrsFontAttribute(aStr, aFontPSName, aFontSize)
  set tmpAttr to NSMutableAttributedString’s alloc()’s initWithString:aStr
  
set aRange to current application’s NSMakeRange(0, tmpAttr’s |length|())
  
set aVal1 to NSFont’s fontWithName:aFontPSName |size|:aFontSize
  
tmpAttr’s beginEditing()
  
tmpAttr’s addAttribute:(NSFontAttributeName) value:aVal1 range:aRange
  
tmpAttr’s endEditing()
  
return tmpAttr
end changeAttrStrsFontAttribute

–指定テキストデータ(atargText)内に、指定文字列(aSearchStr)が含まれる範囲情報(NSRange)をすべて取得する
on searchWordWithRange(aTargText, aSearchStr)
  set aStr to NSString’s stringWithString:aTargText
  
set bStr to NSString’s stringWithString:aSearchStr
  
set hitArray to NSMutableArray’s alloc()’s init()
  
set cNum to (aStr’s |length|()) as integer
  
  
set aRange to current application’s NSMakeRange(0, cNum)
  
  
repeat
    set detectedRange to aStr’s rangeOfString:bStr options:NSLiteralSearch range:aRange
    
set aLoc to (detectedRange’s location)
    
–CAUTION !!!! Sometimes aLoc returns not NSNotFound (-1) but a Very large number
    
if (aLoc > 9.999999999E+9) or (aLoc = (current application’s NSNotFound)) then exit repeat
    
    
hitArray’s addObject:detectedRange
    
    
set aNum to aLoc as integer
    
set bNum to (detectedRange’s |length|) as integer
    
    
set aRange to current application’s NSMakeRange(aNum + bNum, cNum – (aNum + bNum))
  end repeat
  
  
return hitArray
end searchWordWithRange

–スタイル付きテキストを指定フォルダ(POSIX path)にRTFで書き出し
on saveStyledTextAsRTF(targFol, aStyledString)
  set bstyledLength to aStyledString’s |string|()’s |length|()
  
set bDict to NSDictionary’s dictionaryWithObject:"NSRTFTextDocumentType" forKey:(NSDocumentTypeDocumentAttribute)
  
set bRTF to aStyledString’s RTFFromRange:(current application’s NSMakeRange(0, bstyledLength)) documentAttributes:bDict
  
  
set theName to (NSUUID’s UUID()’s UUIDString())
  
set thePath to NSString’s stringWithString:targFol
  
set thePath to (thePath’s stringByAppendingPathComponent:theName)’s stringByAppendingPathExtension:"rtf"
  
return (bRTF’s writeToFile:thePath atomically:true) as boolean
end saveStyledTextAsRTF

–2D迷路を作成して脱出経路を検索して文字列で迷路データを出力する
–迷路サイズ x,y スタート座標 x, y ゴール座標 x,y
on create2DMazeAndSolveIt(xMax, yMax, xStart, yStart, xGoal, yGoal)
  set myBoard to Board2D’s alloc()’s init()
  
myBoard’s setupBoardWithRows:xMax WithColumns:yMax –60×60ぐらいが上限。正方形でないとダメ
  
myBoard’s createMazeFromBoard()
  
  
set myPathfinder to Pathfinder’s alloc()’s init()
  
set myPath to myPathfinder’s findPathThroughMaze:myBoard fromX:xStart fromY:yStart toX:xGoal toY:yGoal
  
  
set aCount to myPath’s |count|()
  
if aCount > 0 then
    set aRes to myBoard’s drawPathThroughMaze:myPath
    
return aRes as string
  else
    return false
  end if
end create2DMazeAndSolveIt

★Click Here to Open This Script 

Posted in Image RTF | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

クリップボードに入ったproperty宣言部分を見た目の描画サイズ(幅)と文字コードでソート

Posted on 2月 6, 2018 by Takaaki Naganoya

クリップボードに入れたproperty宣言文を見た目の描画サイズ(幅)で行単位の並べ替えを行うAppleScriptです。

property文でCocoaのClass名を定義しており、これを整形するために文字数で短いものから長いものへ並べてみたところ、プロポーショナルフォントで表示されるために「美しく」はなりませんでした。実際に仮装画面上でスタイル付きテキストの描画を行って、描画サイズ(幅)を取得して並べ替えを行ってみたものです。

OLD Style AppleScriptの機能の範囲では逆立ちしても実現できない処理内容です。

AppleScript名:クリップボードに入ったproperty宣言部分を見た目の描画サイズ(幅)と文字コードでソート
— Created 2017-12-08 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSFont : a reference to current application’s NSFont
property NSData : a reference to current application’s NSData
property NSColor : a reference to current application’s NSColor
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSDictionary : a reference to current application’s NSDictionary
property NSPasteboard : a reference to current application’s NSPasteboard
property NSCountedSet : a reference to current application’s NSCountedSet
property NSMutableArray : a reference to current application’s NSMutableArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSAttributedString : a reference to current application’s NSAttributedString
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSFontAttributeName : a reference to current application’s NSFontAttributeName
property NSKernAttributeName : a reference to current application’s NSKernAttributeName
property NSMutableParagraphStyle : a reference to current application’s NSMutableParagraphStyle
property NSLigatureAttributeName : a reference to current application’s NSLigatureAttributeName
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSUnderlineStyleAttributeName : a reference to current application’s NSUnderlineStyleAttributeName
property NSParagraphStyleAttributeName : a reference to current application’s NSParagraphStyleAttributeName
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName

–クリップボードの内容を文字列として取得
set aStr to (the clipboard) as string
if aStr = "" then
  display dialog "No Data in Clipboard" buttons {"OK"} default button 1
  
return
end if

–クリップボードの内容をStyled Stringで取得して最頻出フォントを取得
set clipboardAttrStr to getClipboardASStyledText() of me
if clipboardAttrStr = missing value then
  display dialog "Can not get clipboard as Styled String" buttons {"OK"} default button 1
  
return
end if
set attrList to getAttributeRunsFromAttrString(clipboardAttrStr) of me
set anArray to (NSArray’s arrayWithArray:attrList)’s valueForKeyPath:"fontName"
set aFontList to (countItemsByItsAppearance(anArray) of me)
set aFontName to theName of first item of aFontList

–クリップボードから取得した文字データについて処理
set aList to paragraphs of aStr –行ごとにparseしてlist化
set bList to {}
repeat with i in aList
  set j to contents of i
  
if j ≠ {} then
    set jList to words of j
    
if jList ≠ {} then
      if contents of first item of jList = "property" then
        set curLabel to contents of second item of jList
        
        
–行をAttributed Stringとして組み立てて、画面描画時の仕上がりサイズを取得
        
set anAssrStr to makeRTFfromParameters(j, aFontName, 16, -2, 16) of me
        
set aSize to anAssrStr’s |size|() –画面描画時のサイズを取得
        
        
if class of aSize = record then
          set attrStrWidth to width of aSize
          
set attrStrHeight to height of aSize
        else if class of aSize = list then –macOS 10.13.xのバグ回避
          copy aSize to {attrStrWidth, attrStrHeight}
        end if
        
        
set the end of bList to {aLabel:curLabel, aCon:j, aWidth:attrStrWidth}
      end if
    end if
  end if
end repeat

if bList = {} then
  display dialog "Error" buttons {"OK"} default button 1
  
return
end if

–複数キーでソート(書式つきテキストの仕上がりサイズ幅、文字コード順でソート)
set aArray to NSArray’s arrayWithArray:bList
set desc1 to NSSortDescriptor’s sortDescriptorWithKey:"aWidth" ascending:true
set desc2 to NSSortDescriptor’s sortDescriptorWithKey:"aLabel" ascending:true selector:"localizedCaseInsensitiveCompare:"
set bArray to aArray’s sortedArrayUsingDescriptors:{desc1, desc2}

–ソートしたlist of recordからaCon(元のproperty宣言行そのもの)を一括で取り出す
set dArray to (NSMutableArray’s arrayWithArray:bArray)’s valueForKeyPath:"aCon"

–listをデリミタつきのテキストに
set dStr to retStrFromArrayWithDelimiter(dArray, return) of me

set the clipboard to (dStr & return)

–1D Listを文字列長でソート v2
on sort1DListByIndicatedStringLength(aList as list, aSortKey as string, sortOrder as boolean)
  set aArray to NSArray’s arrayWithArray:aList
  
set descLabel1 to NSString’s stringWithString:(aSortKey & ".length")
  
set descLabel2 to NSString’s stringWithString:aSortKey
  
set desc1 to NSSortDescriptor’s sortDescriptorWithKey:descLabel1 ascending:sortOrder
  
set desc2 to NSSortDescriptor’s sortDescriptorWithKey:descLabel2 ascending:true selector:"localizedCaseInsensitiveCompare:"
  
set bArray to aArray’s sortedArrayUsingDescriptors:{desc1, desc2}
  
return bArray as list
end sort1DListByIndicatedStringLength

–リストを指定デリミタをはさんでテキスト化
on retStrFromArrayWithDelimiter(aList as list, aDelim as string)
  set anArray to NSArray’s arrayWithArray:aList
  
set aRes to anArray’s componentsJoinedByString:aDelim
  
return aRes as text
end retStrFromArrayWithDelimiter

–書式つきテキストを組み立てる
on makeRTFfromParameters(aStr as string, fontName as string, aFontSize as real, aKerning as real, aLineSpacing as real)
  set aVal1 to NSFont’s fontWithName:fontName |size|:aFontSize
  
set aKey1 to (NSFontAttributeName)
  
  
set aVal2 to NSColor’s blackColor()
  
set aKey2 to (NSForegroundColorAttributeName)
  
  
set aVal3 to aKerning
  
set akey3 to (NSKernAttributeName)
  
  
set aVal4 to 0
  
set akey4 to (NSUnderlineStyleAttributeName)
  
  
set aVal5 to 2 –all ligature ON
  
set akey5 to (NSLigatureAttributeName)
  
  
set aParagraphStyle to NSMutableParagraphStyle’s alloc()’s init()
  
aParagraphStyle’s setMinimumLineHeight:(aLineSpacing)
  
aParagraphStyle’s setMaximumLineHeight:(aLineSpacing)
  
set akey7 to (NSParagraphStyleAttributeName)
  
  
set keyList to {aKey1, aKey2, akey3, akey4, akey5, akey7}
  
set valList to {aVal1, aVal2, aVal3, aVal4, aVal5, aParagraphStyle}
  
set attrsDictionary to NSMutableDictionary’s dictionaryWithObjects:valList forKeys:keyList
  
  
set attrStr to NSMutableAttributedString’s alloc()’s initWithString:aStr attributes:attrsDictionary
  
return attrStr
end makeRTFfromParameters

— クリップボードの内容をNSAttributedStringとして取り出して返す
on getClipboardASStyledText()
  set theNSPasteboard to NSPasteboard’s generalPasteboard()
  
set theAttributedStringNSArray to theNSPasteboard’s readObjectsForClasses:({NSAttributedString}) options:(missing value)
  
set theNSAttributedString to theAttributedStringNSArray’s objectAtIndex:0
  
return theNSAttributedString
end getClipboardASStyledText

–指定のNSAttributedStringから書式情報をlist of recordで取得
on getAttributeRunsFromAttrString(theStyledText)
  script aSpd
    property styleList : {}
  end script
  
  
set (styleList of aSpd) to {} —for output
  
  
set thePureString to theStyledText’s |string|() –pure string from theStyledText
  
  
set theLength to theStyledText’s |length|()
  
set startIndex to 0
  
  
repeat until (startIndex = theLength)
    set {theAtts, theRange} to theStyledText’s attributesAtIndex:startIndex longestEffectiveRange:(reference) inRange:{startIndex, theLength – startIndex}
    
    
set aText to (thePureString’s substringWithRange:theRange) as string
    
    
set aColor to (theAtts’s valueForKeyPath:"NSColor")
    
if aColor is not equal to missing value then
      set aSpace to aColor’s colorSpace()
      
      
set aRed to (aColor’s redComponent()) * 255
      
set aGreen to (aColor’s greenComponent()) * 255
      
set aBlue to (aColor’s blueComponent()) * 255
      
      
set colList to {aRed as integer, aGreen as integer, aBlue as integer}
      
set colStrForFind to (aRed as integer as string) & " " & (aGreen as integer as string) & " " & (aBlue as integer as string)
    else
      set colList to {0, 0, 0}
      
set colStrForFind to "0 0 0"
    end if
    
    
set aFont to (theAtts’s valueForKeyPath:"NSFont")
    
if aFont is not equal to missing value then
      set aDFontName to aFont’s displayName()
      
set aDFontSize to aFont’s pointSize()
    end if
    
    
set the end of (styleList of aSpd) to {stringVal:aText, colorStr:colStrForFind, colorVal:colList, fontName:aDFontName as string, fontSize:aDFontSize}
    
set startIndex to current application’s NSMaxRange(theRange)
  end repeat
  
  
return (styleList of aSpd)
end getAttributeRunsFromAttrString

–1D Listをアイテムの出現頻度順でソートして返す
on countItemsByItsAppearance(aList as list)
  set aSet to NSCountedSet’s alloc()’s initWithArray:aList
  
set bArray to NSMutableArray’s array()
  
set theEnumerator to aSet’s objectEnumerator()
  
  
repeat
    set aValue to theEnumerator’s nextObject()
    
if aValue is missing value then exit repeat
    
bArray’s addObject:(NSDictionary’s dictionaryWithObjects:{aValue, (aSet’s countForObject:aValue)} forKeys:{"theName", "numberOfTimes"})
  end repeat
  
  
set theDesc to NSSortDescriptor’s sortDescriptorWithKey:"numberOfTimes" ascending:false
  
bArray’s sortUsingDescriptors:{theDesc}
  
  
return bArray as list
end countItemsByItsAppearance

★Click Here to Open This Script 

Posted in Clipboard Image RTF Text | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

Post navigation

  • Older posts
  • Newer posts

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • CotEditorで2つの書類の行単位での差分検出
  • macOS 13.6.5 AS系のバグ、一切直らず
  • macOS 15, Sequoia
  • 初心者がつまづきやすい「log」コマンド
  • 指定のWordファイルをPDFに書き出す
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Adobe AcrobatをAppleScriptから操作してPDF圧縮
  • メキシカンハットの描画
  • 与えられた文字列の1D Listのすべての順列組み合わせパターン文字列を返す v3(ベンチマーク用)
  • 2023年に書いた価値あるAppleScript
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • Numbersで選択範囲のセルの前後の空白を削除
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • Cocoa Scripting Course 続刊計画
  • AppleScriptによる並列処理
  • macOS 14.xでScript Menuの実行速度が大幅に下がるバグ
  • NaturalLanguage.frameworkでNLEmbeddingの処理が可能な言語をチェック
  • AppleScript入門③AppleScriptを使った「自動化」とは?

Tags

10.11savvy (1102) 10.12savvy (1243) 10.13savvy (1392) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (188) 14.0savvy (138) 15.0savvy (116) CotEditor (64) Finder (51) iTunes (19) Keynote (115) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (75) Pages (54) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Beginner
  • Benchmark
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • check sum
  • Clipboard
  • Cocoa-AppleScript Applet
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • diff
  • drive
  • Droplet
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Localize
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • parallel processing
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2025年2月
  • 2025年1月
  • 2024年12月
  • 2024年11月
  • 2024年10月
  • 2024年9月
  • 2024年8月
  • 2024年7月
  • 2024年6月
  • 2024年5月
  • 2024年4月
  • 2024年3月
  • 2024年2月
  • 2024年1月
  • 2023年12月
  • 2023年11月
  • 2023年10月
  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC