FolderAction

[FolderAction]【自分用】スクリーンキャプチャ・フォルダアクション(リサイズから日本語OCRまで)修正



ダウンロード - screencap_folderaction.zip




AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004# トリガーとしてファイルのパスを受け取るが使わないパターン
005# OCR処理にmissing value対策を追加
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "AppKit"
010use framework "CoreImage"
011use framework "VisionKit"
012use framework "Vision"
013use scripting additions
014property refMe : a reference to current application
015
016
017on run {argListFilePath}
018#単体実行用
019  #on run
020  
021  ###########################
022  #必要なフォルダ
023  set appFileManager to refMe's NSFileManager's defaultManager()
024  #Picturesフォルダ
025  set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
026  set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
027  set ocidAutomatorExportDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/AutomatorExport") isDirectory:(true))
028  set ocidExportAutomatorDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/ExportAutomator") isDirectory:(true))
029  set ocidExportSmallDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/ExportSmall") isDirectory:(true))
030  set ocidExportTiffDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/ExportTiff") isDirectory:(true))
031  set ocidPostImageDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/PostImage") isDirectory:(true))
032  set ocidScreenCaptureDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/ScreenCapture") isDirectory:(true))
033  set ocidTemporaryItemsDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/TemporaryItems") isDirectory:(true))
034  set ocidWorkFileDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/WorkFile") isDirectory:(true))
035  
036  
037  ###########################
038  #【1】ファイルの収集
039  set appFileManager to refMe's NSFileManager's defaultManager()
040  set ocidOptions to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
041  set ocidKeyArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
042  ocidKeyArray's addObject:(refMe's NSURLPathKey)
043  set listResponse to appFileManager's contentsOfDirectoryAtURL:(ocidScreenCaptureDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOptions) |error| :(reference)
044  if (item 2 of listResponse) = (missing value) then
045    set ocidScreenCaptureURLArray to (item 1 of listResponse)
046    log "【1】ファイルの収集"
047  else if (item 2 of listDone) ≠ (missing value) then
048    log ((item 2 of listDone)'s localizedDescription()) as text
049    return display alert "【1】ファイルの収集に失敗しました"
050  end if
051  
052  
053  ###########################
054  #【2】移動
055  #収集したファイルを処理
056  repeat with itemURL in ocidScreenCaptureURLArray
057    #拡張子
058    set ocidExtensionName to itemURL's pathExtension()
059    #UUIDを取得して
060    set ocidUUID to refMe's NSUUID's alloc()'s init()
061    set ocidUUIDString to ocidUUID's UUIDString
062    #移動先
063    set ocidDistBaseFilePathURL to (ocidWorkFileDirPathURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:(false))
064    #拡張子追加
065    set ocidDistFilePathURL to (ocidDistBaseFilePathURL's URLByAppendingPathExtension:(ocidExtensionName))
066    #移動
067    set listDone to (appFileManager's moveItemAtURL:(itemURL) toURL:(ocidDistFilePathURL) |error| :(reference))
068    if (item 1 of listDone) is true then
069      log "【2】移動しました"
070    else if (item 2 of listDone) ≠ (missing value) then
071      log ((item 2 of listDone)'s localizedDescription()) as text
072      return display alert "【2】ファイルの移動に失敗しました"
073    end if
074  end repeat
075  
076  ###########################
077  #【3】ファイルの収集
078  set appFileManager to refMe's NSFileManager's defaultManager()
079  set ocidOptions to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
080  set ocidKeyArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
081  ocidKeyArray's addObject:(refMe's NSURLPathKey)
082  set listResponse to appFileManager's contentsOfDirectoryAtURL:(ocidWorkFileDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOptions) |error| :(reference)
083  if (item 2 of listResponse) = (missing value) then
084    set ocidWorkFileURLArray to (item 1 of listResponse)
085    log "【3】ファイルの収集"
086  else if (item 2 of listDone) ≠ (missing value) then
087    log ((item 2 of listDone)'s localizedDescription()) as text
088    return display alert "【3】ファイルの収集に失敗しました"
089  end if
090  
091  ###########################
092  #【4】72ppiにする
093  repeat with itemURL in ocidWorkFileURLArray
094    #
095    set ocidOption to (refMe's NSDataReadingMappedIfSafe)
096    set listReadData to (refMe's NSData's alloc()'s initWithContentsOfURL:(itemURL) options:(ocidOption) |error| :(reference))
097    if (item 2 of listReadData) ≠ (missing value) then
098      log (item 2 of listReadStings)'s localizedDescription() as text
099      return display alert "【4】データの読み込みに失敗しました"
100    else
101      log "【4】データの読み込み"
102      set ocidReadData to (item 1 of listReadData)
103    end if
104    #NSIMAGEに読み込む
105    set ocidReadImage to (refMe's NSImage's alloc()'s initWithData:(ocidReadData))
106    #サイズPT
107    set recordSize to ocidReadImage's |size|()
108    set numWidthPtSize to (recordSize's width) as number
109    set numHeightPtSize to (recordSize's height) as number
110    ##BitMapRepに変換
111    set ocidReadImageRepArray to ocidReadImage's representations()
112    set ocidReadImageRep to ocidReadImageRepArray's firstObject()
113    ##ピクセルサイズ取得
114    set numPixelsWidth to ocidReadImageRep's pixelsWide()
115    set numPixelsHeight to ocidReadImageRep's pixelsHigh()
116    #まず72ppiにする
117    set ocidPixelsSize to refMe's NSSize's NSMakeSize(numPixelsWidth, numPixelsHeight)
118    (ocidReadImageRep's setSize:(ocidPixelsSize))
119    #保存オプション
120    set ocidSaveImageType to (refMe's NSBitmapImageFileTypePNG)
121    #カラーICC
122    set strIccFilePath to ("/System/Library/ColorSync/Profiles/sRGB Profile.icc") as text
123    set ocidIccFilePathStr to (refMe's NSString's stringWithString:(strIccFilePath))
124    set ocidIccFilePath to ocidIccFilePathStr's stringByStandardizingPath
125    set ocidIccFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidIccFilePath) isDirectory:(false))
126    set ocidProfileData to (refMe's NSData's alloc()'s initWithContentsOfURL:(ocidIccFilePathURL))
127    #保存オプション
128    set ocidPropertiesDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
129    (ocidPropertiesDict's setObject:(refMe's NSNumber's numberWithBool:false) forKey:(refMe's NSImageInterlaced))
130    (ocidPropertiesDict's setObject:(refMe's NSNumber's numberWithDouble:(1 / 2.2)) forKey:(refMe's NSImageGamma))
131    (ocidPropertiesDict's setObject:(ocidProfileData) forKey:(refMe's NSImageColorSyncProfileData))
132    #イメージ変換
133    set ocidSaveImageData to (ocidReadImageRep's representationUsingType:(ocidSaveImageType) |properties|:(ocidPropertiesDict))
134    #保存
135    set listDone to (ocidSaveImageData's writeToURL:(itemURL) options:(refMe's NSDataWritingAtomic) |error| :(reference))
136    if (item 2 of listDone) ≠ (missing value) then
137      log (item 2 of listDone)'s localizedDescription() as text
138      return display alert "【4】データの保存に失敗しました"
139    else
140      set ocidReadData to (item 1 of listDone)
141    end if
142  end repeat
143  
144  ###########################
145  #【5】移動
146  #収集したファイルを処理
147  repeat with itemURL in ocidWorkFileURLArray
148    #ファイル名
149    set ocidFileName to itemURL's lastPathComponent()
150    #移動先
151    set ocidDistFilePathURL to (ocidExportAutomatorDirPathURL's URLByAppendingPathComponent:(ocidFileName) isDirectory:(false))
152    #移動
153    set listDone to (appFileManager's moveItemAtURL:(itemURL) toURL:(ocidDistFilePathURL) |error| :(reference))
154    if (item 1 of listDone) is true then
155      log "【5】移動しました"
156    else if (item 2 of listDone) ≠ (missing value) then
157      log ((item 2 of listDone)'s localizedDescription()) as text
158      return display alert "【5】ファイルの移動に失敗しました"
159    end if
160  end repeat
161  
162  
163  ###########################
164  #【6】ファイルの収集
165  set appFileManager to refMe's NSFileManager's defaultManager()
166  set ocidOptions to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
167  set ocidKeyArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
168  ocidKeyArray's addObject:(refMe's NSURLPathKey)
169  set listResponse to appFileManager's contentsOfDirectoryAtURL:(ocidExportAutomatorDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOptions) |error| :(reference)
170  if (item 2 of listResponse) = (missing value) then
171    set ocidExportAutomatorURLArray to (item 1 of listResponse)
172    log "【6】ファイルの収集"
173  else if (item 2 of listDone) ≠ (missing value) then
174    log ((item 2 of listDone)'s localizedDescription()) as text
175    return display alert "【6】ファイルの収集に失敗しました"
176  end if
177  
178  
179  ###########################
180  #【7】 TIFF 出力
181  #日付時間の取得
182  set strDateNo to doGetDateNo("yyyyMMdd-hhmmss") as text
183  #カウンター
184  set numCntNo to 1 as integer
185  #本処理
186  repeat with itemURL in ocidExportAutomatorURLArray
187    #データ読み込み
188    set ocidOption to (refMe's NSDataReadingMappedIfSafe)
189    set listReadData to (refMe's NSData's alloc()'s initWithContentsOfURL:(itemURL) options:(ocidOption) |error| :(reference))
190    if (item 2 of listReadData) ≠ (missing value) then
191      log (item 2 of listReadStings)'s localizedDescription() as text
192      return display alert "【7】データの読み込みに失敗しました"
193    else
194      log "【7】データの読み込み"
195      set ocidReadData to (item 1 of listReadData)
196      #NSIMAGEに読み込む
197      set ocidReadImage to (refMe's NSImage's alloc()'s initWithData:(ocidReadData))
198      #BitMapRepに変換
199      set ocidReadImageRepArray to ocidReadImage's representations()
200      set ocidReadImageRep to ocidReadImageRepArray's firstObject()
201      ##ピクセルサイズ取得
202      set numPixelsWidth to ocidReadImageRep's pixelsWide()
203      set numPixelsHeight to ocidReadImageRep's pixelsHigh()
204      #ファイル名
205      set strSaveFileName to (strDateNo & "-" & numCntNo & "_" & numPixelsWidth & "x" & numPixelsHeight) as text
206      set ocidTiffBasePathURL to (ocidExportTiffDirPathURL's URLByAppendingPathComponent:(strSaveFileName) isDirectory:(false))
207      set ocidTiffFilePathURL to (ocidTiffBasePathURL's URLByAppendingPathExtension:("tiff"))
208      #NSDATAに変換
209      set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
210      (ocidPropertyDict's setObject:(refMe's NSTIFFCompressionNone) forKey:(refMe's NSImageCompressionMethod))
211      (ocidPropertyDict's setObject:(refMe's NSNumber's numberWithFloat:(0)) forKey:(refMe's NSImageCompressionFactor))
212      #TIFF 変換
213      set ocidSaveImageType to (refMe's NSBitmapImageFileTypeTIFF)
214      set ocidSaveImageData to (ocidReadImageRep's representationUsingType:(ocidSaveImageType) |properties|:(ocidPropertyDict))
215      #保存
216      set listDone to (ocidSaveImageData's writeToURL:(ocidTiffFilePathURL) options:(refMe's NSDataWritingAtomic) |error| :(reference))
217      if (item 2 of listDone) ≠ (missing value) then
218        log (item 2 of listDone)'s localizedDescription() as text
219        return display alert "【7】データの保存に失敗しました"
220      else
221        set ocidReadData to (item 1 of listDone)
222      end if
223      #カウントアップ
224      set numCntNo to numCntNo + 1 as integer
225    end if
226  end repeat
227  
228  
229  ###########################
230  #【8】 Small 出力
231  #カウンター
232  set numCntNo to 1 as integer
233  #本処理
234  repeat with itemURL in ocidExportAutomatorURLArray
235    #読み込み
236    set ocidOption to (refMe's NSDataReadingMappedIfSafe)
237    set listReadData to (refMe's NSData's alloc()'s initWithContentsOfURL:(itemURL) options:(ocidOption) |error| :(reference))
238    if (item 2 of listReadData) ≠ (missing value) then
239      log (item 2 of listReadStings)'s localizedDescription() as text
240      return display alert "【8】データの読み込みに失敗しました"
241    else
242      log "【8】データの読み込み"
243      set ocidReadData to (item 1 of listReadData)
244    end if
245    #NSIMAGEに読み込む
246    set ocidReadImage to (refMe's NSImage's alloc()'s initWithData:(ocidReadData))
247    #BitMapRepに変換
248    set ocidReadImageRepArray to ocidReadImage's representations()
249    set ocidReadImageRep to ocidReadImageRepArray's firstObject()
250    ##ピクセルサイズ取得
251    set numPixelsWidth to ocidReadImageRep's pixelsWide()
252    set numPixelsHeight to ocidReadImageRep's pixelsHigh()
253    #半分サイズ(数値の丸めで1ピクセルの誤差を容認)
254    set numSmallWidth to (numPixelsWidth / 2) as integer
255    set numSmallHeight to (numPixelsHeight / 2) as integer
256    set ocidSmallSize to refMe's NSSize's NSMakeSize(numSmallWidth, numSmallHeight)
257    set ocidSmallRect to refMe's NSRect's NSMakeRect(0, 0, numSmallWidth, numSmallHeight)
258    #出力用イメージ NSBitmapImageRep
259    # samplesPerPixel
260    set intSPP to 4 as integer
261    # bitsPerSample
262    set intBPS to 8 as integer
263    # bytesPerRow
264    set intBPR to (numSmallWidth * intSPP) as integer
265    # bitsPerPixel
266    set intBPP to 32 as integer
267    # RGB系のカラースペース
268    set ocidColorSpaceName to refMe's NSCalibratedRGBColorSpace
269    # アルファあり
270    set ocidBitmapFormat to refMe's NSAlphaFirstBitmapFormat
271    ##出力ピクセルサイズのブランクイメージ
272    set ocidArtBoardRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numSmallWidth) pixelsHigh:(numSmallHeight) bitsPerSample:(intBPS) samplesPerPixel:(intSPP) hasAlpha:(true) isPlanar:(false) colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:(intBPR) bitsPerPixel:(intBPP))
273    #ArtBord
274    ### 初期化 CodeBase
275    refMe's NSGraphicsContext's saveGraphicsState()
276    ###Context
277    set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
278    ###生成された画像でNSGraphicsContext初期化
279    (refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
280    ##色を個別に指定する場合 値は0が暗 1が明
281    set ocidSetColor to (refMe's NSColor's colorWithSRGBRed:(1.0) green:(1.0) blue:(1.0) alpha:(0.0))
282    ocidSetColor's |set|()
283    ###画像生成
284    refMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:(numSmallWidth), height:(numSmallHeight)}})
285    #画像作成終了
286    refMe's NSGraphicsContext's restoreGraphicsState()
287    #合成 リザイスでNSCompositeSourceOver
288    ### 初期化
289    refMe's NSGraphicsContext's saveGraphicsState()
290    ###Context
291    set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
292    ###NSGraphicsContext初期化
293    (refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
294    ####NSCompositeSourceOver
295    set ocidDrawInRect to {origin:{x:(0), y:(0)}, |size|:{width:(numSmallWidth), Hight:(numSmallHeight)}}
296    set ocidFromRect to (refMe's NSZeroRect)
297    # set ocidOption to (refMe's NSCompositeSourceOver)
298    set ocidOption to (refMe's NSCompositingOperationSourceOver)
299    ##  set ocidOption to (refMe's NSCompositeCopy)
300    (ocidReadImageRep's drawInRect:(ocidDrawInRect) fromRect:(ocidFromRect) operation:(ocidOption) fraction:1.0 respectFlipped:true hints:(missing value))
301    #画像作成終了
302    refMe's NSGraphicsContext's restoreGraphicsState()
303    #保存オプション
304    set ocidProperty to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
305    (ocidProperty's setObject:(refMe's NSNumber's numberWithBool:false) forKey:(refMe's NSImageInterlaced))
306    (ocidProperty's setObject:(refMe's NSNumber's numberWithDouble:(1 / 2.2)) forKey:(refMe's NSImageGamma))
307    ##保存
308    set ocidNSInlineData to (ocidArtBoardRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
309    #スモールの保存先
310    set strSmallFileName to (strDateNo & "-" & numCntNo & "_" & numSmallWidth & "x" & numSmallHeight) as text
311    set ocidExportSmallBasePathURL to (ocidExportSmallDirPathURL's URLByAppendingPathComponent:(strSmallFileName) isDirectory:(false))
312    set ocidExportSmallPathURL to (ocidExportSmallBasePathURL's URLByAppendingPathExtension:("png"))
313    
314    set ocidOption to (refMe's NSDataWritingAtomic)
315    set listDone to (ocidNSInlineData's writeToURL:(ocidExportSmallPathURL) options:(ocidOption) |error| :(reference))
316    if (item 1 of listDone) is true then
317      log "【8】保存しました"
318    else if (item 2 of listDone) ≠ (missing value) then
319      log ((item 2 of listDone)'s localizedDescription()) as text
320      return display alert "Automator【8】保存に失敗しました"
321    end if
322    #カウントアップ
323    set numCntNo to numCntNo + 1 as integer
324  end repeat
325  
326  
327  ###########################
328  #【9】OCR作成して移動
329  #カウンター
330  set numCntNo to 1 as integer
331  #収集したファイルを処理
332  repeat with itemURL in ocidExportAutomatorURLArray
333    set ocidOption to (refMe's NSDataReadingMappedIfSafe)
334    set listReadData to (refMe's NSData's alloc()'s initWithContentsOfURL:(itemURL) options:(ocidOption) |error| :(reference))
335    if (item 2 of listReadData) ≠ (missing value) then
336      log (item 2 of listReadStings)'s localizedDescription() as text
337      return display alert "【9】データの読み込みに失敗しました"
338    else
339      log "【9】データの読み込み"
340      set ocidReadData to (item 1 of listReadData)
341    end if
342    #OCRを先に処理
343    #最小フォントサイズ
344    set numMinPt to 8 as integer
345    #####ImageRep画像の高さを取得
346    ##画像に対しての8Ptテキストの比率--> MinimumTextHeightにセットする
347    set ocidImageRep to (refMe's NSBitmapImageRep's imageRepWithData:(ocidReadData))
348    ##ピクセルサイズ取得
349    set numPixelsWidth to ocidReadImageRep's pixelsWide()
350    set numPixelsHeight to ocidReadImageRep's pixelsHigh()
351    set intTextHeight to (numMinPt / numPixelsHeight) as number
352    #####OCR
353    #VNImageRequestHandler's
354    set ocidHandler to (refMe's VNImageRequestHandler's alloc()'s initWithData:(ocidReadData) options:(missing value))
355    #VNRecognizeTextRequest's
356    set ocidRequest to refMe's VNRecognizeTextRequest's alloc()'s init()
357    set ocidOption to (refMe's VNRequestTextRecognitionLevelAccurate)
358    (ocidRequest's setRecognitionLevel:(ocidOption))
359    (ocidRequest's setMinimumTextHeight:(intTextHeight))
360    (ocidRequest's setAutomaticallyDetectsLanguage:(true))
361    (ocidRequest's setRecognitionLanguages:{"en", "ja"})
362    (ocidRequest's setUsesLanguageCorrection:(false))
363    #results
364    (ocidHandler's performRequests:(refMe's NSArray's arrayWithObject:(ocidRequest)) |error| :(reference))
365    set ocidResponseArray to ocidRequest's results()
366    #戻り値を格納するテキスト
367    set ocidFirstOpinionString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
368    set ocidSecondOpinionString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
369    set ocidSaveString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
370    #missing value対策
371    if ocidResponseArray = (missing value) then
372      (ocidFirstOpinionString's appendString:("テキストは認識されませんでした"))
373      (ocidSecondOpinionString's appendString:("テキストは認識されませんでした"))
374    else
375      #戻り値の数だけ々
376      repeat with itemArray in ocidResponseArray
377        #候補数指定 1−10 ここでは2種の候補を戻す指定
378        set ocidRecognizedTextArray to (itemArray's topCandidates:(2))
379        set ocidFirstOpinion to ocidRecognizedTextArray's firstObject()
380        set ocidSecondOpinion to ocidRecognizedTextArray's lastObject()
381        (ocidFirstOpinionString's appendString:(ocidFirstOpinion's |string|()))
382        (ocidFirstOpinionString's appendString:("\r"))
383        (ocidSecondOpinionString's appendString:(ocidSecondOpinion's |string|()))
384        (ocidSecondOpinionString's appendString:("\r"))
385      end repeat
386    end if
387    ##比較して相違点を探すならここで
388    (ocidSaveString's appendString:("-----第1候補\r\r"))
389    (ocidSaveString's appendString:(ocidFirstOpinionString))
390    (ocidSaveString's appendString:("\r\r-----第2候補\r\r"))
391    (ocidSaveString's appendString:(ocidSecondOpinionString))
392    ##
393    set strOCRFileName to (strDateNo & "-" & numCntNo & "_" & numPixelsWidth & "x" & numPixelsHeight) as text
394    set ocidAutomatorExportBasePathURL to (ocidAutomatorExportDirPathURL's URLByAppendingPathComponent:(strOCRFileName) isDirectory:(false))
395    set ocidOcrSaveFilePathURL to (ocidAutomatorExportBasePathURL's URLByAppendingPathExtension:("txt"))
396    #保存
397    set listDone to (ocidSaveString's writeToURL:(ocidOcrSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference))
398    if (item 1 of listDone) is true then
399      log "【9】正常終了"
400    else if (item 1 of listDone) is false then
401      log (item 2 of listDone)'s localizedDescription() as text
402      return display alert " 【9】 OCR保存に失敗しました"
403    end if
404    set ocidImageRep to ""
405    set ocidReadData to ""
406    set ocidMoveFilePathURL to (ocidAutomatorExportBasePathURL's URLByAppendingPathExtension:("png"))
407    set appFileManager to refMe's NSFileManager's defaultManager()
408    set listDone to (appFileManager's moveItemAtURL:(itemURL) toURL:(ocidMoveFilePathURL) |error| :(reference))
409    if (item 1 of listDone) is true then
410      log "【9】移動しました"
411    else if (item 2 of listDone) ≠ (missing value) then
412      log ((item 2 of listDone)'s localizedDescription()) as text
413      return display alert "Automator【9】移動に失敗しました"
414    end if
415    #カウントアップ
416    set numCntNo to numCntNo + 1 as integer
417    
418    
419  end repeat
420  
421  
422end run
423
424
425################################
426# 日付 doGetDateNo()
427################################
428to doGetDateNo(strDateFormat)
429  ####日付情報の取得
430  set ocidDate to current application's NSDate's |date|()
431  ###日付のフォーマットを定義
432  set ocidNSDateFormatter to current application's NSDateFormatter's alloc()'s init()
433  ocidNSDateFormatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
434  ocidNSDateFormatter's setDateFormat:strDateFormat
435  set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate
436  set strDateAndTime to ocidDateAndTime as text
437  return strDateAndTime
438end doGetDateNo
AppleScriptで生成しました

|

[FolderAction]【自分用】スクリーンキャプチャ・フォルダアクション(リサイズから日本語OCRまで)途中



ダウンロード - screencap_folderaction.zip




AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# 途中だけどいちおう動作はする
004# トリガーとしてファイルのパスを受け取るが使わないパターン
005#com.cocolog-nifty.quicktimer.icefloe
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "AppKit"
010use framework "CoreImage"
011use framework "VisionKit"
012use framework "Vision"
013use scripting additions
014property refMe : a reference to current application
015
016
017on run {argListFilePath}
018  
019  
020  ###########################
021  #必要なフォルダ
022  set appFileManager to refMe's NSFileManager's defaultManager()
023  #Picturesフォルダ
024  set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
025  set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
026  set ocidAutomatorExportDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/AutomatorExport") isDirectory:(true))
027  set ocidExportAutomatorDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/ExportAutomator") isDirectory:(true))
028  set ocidExportSmallDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/ExportSmall") isDirectory:(true))
029  set ocidExportTiffDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/ExportTiff") isDirectory:(true))
030  set ocidPostImageDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/PostImage") isDirectory:(true))
031  set ocidScreenCaptureDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/ScreenCapture") isDirectory:(true))
032  set ocidTemporaryItemsDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/TemporaryItems") isDirectory:(true))
033  set ocidWorkFileDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/WorkFile") isDirectory:(true))
034  
035  
036  ###########################
037  #【1】ファイルの収集
038  set appFileManager to refMe's NSFileManager's defaultManager()
039  set ocidOptions to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
040  set ocidKeyArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
041  ocidKeyArray's addObject:(refMe's NSURLPathKey)
042  set listResponse to appFileManager's contentsOfDirectoryAtURL:(ocidScreenCaptureDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOptions) |error| :(reference)
043  if (item 2 of listResponse) = (missing value) then
044    set ocidScreenCaptureURLArray to (item 1 of listResponse)
045    log "【1】ファイルの収集"
046  else if (item 2 of listDone) ≠ (missing value) then
047    log ((item 2 of listDone)'s localizedDescription()) as text
048    return display alert "【1】ファイルの収集に失敗しました"
049  end if
050  
051  
052  ###########################
053  #【2】移動
054  #収集したファイルを処理
055  repeat with itemURL in ocidScreenCaptureURLArray
056    #拡張子
057    set ocidExtensionName to itemURL's pathExtension()
058    #UUIDを取得して
059    set ocidUUID to refMe's NSUUID's alloc()'s init()
060    set ocidUUIDString to ocidUUID's UUIDString
061    #移動先
062    set ocidDistBaseFilePathURL to (ocidWorkFileDirPathURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:(false))
063    #拡張子追加
064    set ocidDistFilePathURL to (ocidDistBaseFilePathURL's URLByAppendingPathExtension:(ocidExtensionName))
065    #移動
066    set listDone to (appFileManager's moveItemAtURL:(itemURL) toURL:(ocidDistFilePathURL) |error| :(reference))
067    if (item 1 of listDone) is true then
068      log "【2】移動しました"
069    else if (item 2 of listDone) ≠ (missing value) then
070      log ((item 2 of listDone)'s localizedDescription()) as text
071      return display alert "【2】ファイルの移動に失敗しました"
072    end if
073  end repeat
074  
075  ###########################
076  #【3】ファイルの収集
077  set appFileManager to refMe's NSFileManager's defaultManager()
078  set ocidOptions to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
079  set ocidKeyArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
080  ocidKeyArray's addObject:(refMe's NSURLPathKey)
081  set listResponse to appFileManager's contentsOfDirectoryAtURL:(ocidWorkFileDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOptions) |error| :(reference)
082  if (item 2 of listResponse) = (missing value) then
083    set ocidWorkFileURLArray to (item 1 of listResponse)
084    log "【3】ファイルの収集"
085  else if (item 2 of listDone) ≠ (missing value) then
086    log ((item 2 of listDone)'s localizedDescription()) as text
087    return display alert "【3】ファイルの収集に失敗しました"
088  end if
089  
090  ###########################
091  #【4】72ppiにする
092  repeat with itemURL in ocidWorkFileURLArray
093    #
094    set ocidOption to (refMe's NSDataReadingMappedIfSafe)
095    set listReadData to (refMe's NSData's alloc()'s initWithContentsOfURL:(itemURL) options:(ocidOption) |error| :(reference))
096    if (item 2 of listReadData) ≠ (missing value) then
097      log (item 2 of listReadStings)'s localizedDescription() as text
098      return display alert "【4】データの読み込みに失敗しました"
099    else
100      log "【4】データの読み込み"
101      set ocidReadData to (item 1 of listReadData)
102    end if
103    #NSIMAGEに読み込む
104    set ocidReadImage to (refMe's NSImage's alloc()'s initWithData:(ocidReadData))
105    #サイズPT
106    set recordSize to ocidReadImage's |size|()
107    set numWidthPtSize to (recordSize's width) as number
108    set numHeightPtSize to (recordSize's height) as number
109    ##BitMapRepに変換
110    set ocidReadImageRepArray to ocidReadImage's representations()
111    set ocidReadImageRep to ocidReadImageRepArray's firstObject()
112    ##ピクセルサイズ取得
113    set numPixelsWidth to ocidReadImageRep's pixelsWide()
114    set numPixelsHeight to ocidReadImageRep's pixelsHigh()
115    #まず72ppiにする
116    set ocidPixelsSize to refMe's NSSize's NSMakeSize(numPixelsWidth, numPixelsHeight)
117    (ocidReadImageRep's setSize:(ocidPixelsSize))
118    #保存オプション
119    set ocidSaveImageType to (refMe's NSBitmapImageFileTypePNG)
120    #カラーICC
121    set strIccFilePath to ("/System/Library/ColorSync/Profiles/sRGB Profile.icc") as text
122    set ocidIccFilePathStr to (refMe's NSString's stringWithString:(strIccFilePath))
123    set ocidIccFilePath to ocidIccFilePathStr's stringByStandardizingPath
124    set ocidIccFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidIccFilePath) isDirectory:(false))
125    set ocidProfileData to (refMe's NSData's alloc()'s initWithContentsOfURL:(ocidIccFilePathURL))
126    #保存オプション
127    set ocidPropertiesDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
128    (ocidPropertiesDict's setObject:(refMe's NSNumber's numberWithBool:false) forKey:(refMe's NSImageInterlaced))
129    (ocidPropertiesDict's setObject:(refMe's NSNumber's numberWithDouble:(1 / 2.2)) forKey:(refMe's NSImageGamma))
130    (ocidPropertiesDict's setObject:(ocidProfileData) forKey:(refMe's NSImageColorSyncProfileData))
131    #イメージ変換
132    set ocidSaveImageData to (ocidReadImageRep's representationUsingType:(ocidSaveImageType) |properties|:(ocidPropertiesDict))
133    #保存
134    set listDone to (ocidSaveImageData's writeToURL:(itemURL) options:(refMe's NSDataWritingAtomic) |error| :(reference))
135    if (item 2 of listDone) ≠ (missing value) then
136      log (item 2 of listDone)'s localizedDescription() as text
137      return display alert "【4】データの保存に失敗しました"
138    else
139      set ocidReadData to (item 1 of listDone)
140    end if
141  end repeat
142  
143  ###########################
144  #【5】移動
145  #収集したファイルを処理
146  repeat with itemURL in ocidWorkFileURLArray
147    #ファイル名
148    set ocidFileName to itemURL's lastPathComponent()
149    #移動先
150    set ocidDistFilePathURL to (ocidExportAutomatorDirPathURL's URLByAppendingPathComponent:(ocidFileName) isDirectory:(false))
151    #移動
152    set listDone to (appFileManager's moveItemAtURL:(itemURL) toURL:(ocidDistFilePathURL) |error| :(reference))
153    if (item 1 of listDone) is true then
154      log "【5】移動しました"
155    else if (item 2 of listDone) ≠ (missing value) then
156      log ((item 2 of listDone)'s localizedDescription()) as text
157      return display alert "【5】ファイルの移動に失敗しました"
158    end if
159  end repeat
160  
161  
162  ###########################
163  #【6】ファイルの収集
164  set appFileManager to refMe's NSFileManager's defaultManager()
165  set ocidOptions to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
166  set ocidKeyArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
167  ocidKeyArray's addObject:(refMe's NSURLPathKey)
168  set listResponse to appFileManager's contentsOfDirectoryAtURL:(ocidExportAutomatorDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOptions) |error| :(reference)
169  if (item 2 of listResponse) = (missing value) then
170    set ocidExportAutomatorURLArray to (item 1 of listResponse)
171    log "【6】ファイルの収集"
172  else if (item 2 of listDone) ≠ (missing value) then
173    log ((item 2 of listDone)'s localizedDescription()) as text
174    return display alert "【6】ファイルの収集に失敗しました"
175  end if
176  
177  
178  ###########################
179  #【7】 TIFF 出力
180  #日付時間の取得
181  set strDateNo to doGetDateNo("yyyyMMdd-hhmmss") as text
182  #カウンター
183  set numCntNo to 1 as integer
184  #本処理
185  repeat with itemURL in ocidExportAutomatorURLArray
186    #データ読み込み
187    set ocidOption to (refMe's NSDataReadingMappedIfSafe)
188    set listReadData to (refMe's NSData's alloc()'s initWithContentsOfURL:(itemURL) options:(ocidOption) |error| :(reference))
189    if (item 2 of listReadData) ≠ (missing value) then
190      log (item 2 of listReadStings)'s localizedDescription() as text
191      return display alert "【7】データの読み込みに失敗しました"
192    else
193      log "【7】データの読み込み"
194      set ocidReadData to (item 1 of listReadData)
195      #NSIMAGEに読み込む
196      set ocidReadImage to (refMe's NSImage's alloc()'s initWithData:(ocidReadData))
197      #BitMapRepに変換
198      set ocidReadImageRepArray to ocidReadImage's representations()
199      set ocidReadImageRep to ocidReadImageRepArray's firstObject()
200      ##ピクセルサイズ取得
201      set numPixelsWidth to ocidReadImageRep's pixelsWide()
202      set numPixelsHeight to ocidReadImageRep's pixelsHigh()
203      #ファイル名
204      set strSaveFileName to (strDateNo & "-" & numCntNo & "_" & numPixelsWidth & "x" & numPixelsHeight) as text
205      set ocidTiffBasePathURL to (ocidExportTiffDirPathURL's URLByAppendingPathComponent:(strSaveFileName) isDirectory:(false))
206      set ocidTiffFilePathURL to (ocidTiffBasePathURL's URLByAppendingPathExtension:("tiff"))
207      #NSDATAに変換
208      set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
209      (ocidPropertyDict's setObject:(refMe's NSTIFFCompressionNone) forKey:(refMe's NSImageCompressionMethod))
210      (ocidPropertyDict's setObject:(refMe's NSNumber's numberWithFloat:(0)) forKey:(refMe's NSImageCompressionFactor))
211      #TIFF 変換
212      set ocidSaveImageType to (refMe's NSBitmapImageFileTypeTIFF)
213      set ocidSaveImageData to (ocidReadImageRep's representationUsingType:(ocidSaveImageType) |properties|:(ocidPropertyDict))
214      #保存
215      set listDone to (ocidSaveImageData's writeToURL:(ocidTiffFilePathURL) options:(refMe's NSDataWritingAtomic) |error| :(reference))
216      if (item 2 of listDone) ≠ (missing value) then
217        log (item 2 of listDone)'s localizedDescription() as text
218        return display alert "【7】データの保存に失敗しました"
219      else
220        set ocidReadData to (item 1 of listDone)
221      end if
222      #カウントアップ
223      set numCntNo to numCntNo + 1 as integer
224    end if
225  end repeat
226  
227  
228  ###########################
229  #【8】 Small 出力
230  #カウンター
231  set numCntNo to 1 as integer
232  #本処理
233  repeat with itemURL in ocidExportAutomatorURLArray
234    #読み込み
235    set ocidOption to (refMe's NSDataReadingMappedIfSafe)
236    set listReadData to (refMe's NSData's alloc()'s initWithContentsOfURL:(itemURL) options:(ocidOption) |error| :(reference))
237    if (item 2 of listReadData) ≠ (missing value) then
238      log (item 2 of listReadStings)'s localizedDescription() as text
239      return display alert "【8】データの読み込みに失敗しました"
240    else
241      log "【8】データの読み込み"
242      set ocidReadData to (item 1 of listReadData)
243    end if
244    #NSIMAGEに読み込む
245    set ocidReadImage to (refMe's NSImage's alloc()'s initWithData:(ocidReadData))
246    #BitMapRepに変換
247    set ocidReadImageRepArray to ocidReadImage's representations()
248    set ocidReadImageRep to ocidReadImageRepArray's firstObject()
249    ##ピクセルサイズ取得
250    set numPixelsWidth to ocidReadImageRep's pixelsWide()
251    set numPixelsHeight to ocidReadImageRep's pixelsHigh()
252    #半分サイズ(数値の丸めで1ピクセルの誤差を容認)
253    set numSmallWidth to (numPixelsWidth / 2) as integer
254    set numSmallHeight to (numPixelsHeight / 2) as integer
255    set ocidSmallSize to refMe's NSSize's NSMakeSize(numSmallWidth, numSmallHeight)
256    set ocidSmallRect to refMe's NSRect's NSMakeRect(0, 0, numSmallWidth, numSmallHeight)
257    #出力用イメージ NSBitmapImageRep
258    # samplesPerPixel
259    set intSPP to 4 as integer
260    # bitsPerSample
261    set intBPS to 8 as integer
262    # bytesPerRow
263    set intBPR to (numSmallWidth * intSPP) as integer
264    # bitsPerPixel
265    set intBPP to 32 as integer
266    # RGB系のカラースペース
267    set ocidColorSpaceName to refMe's NSCalibratedRGBColorSpace
268    # アルファあり
269    set ocidBitmapFormat to refMe's NSAlphaFirstBitmapFormat
270    ##出力ピクセルサイズのブランクイメージ
271    set ocidArtBoardRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numSmallWidth) pixelsHigh:(numSmallHeight) bitsPerSample:(intBPS) samplesPerPixel:(intSPP) hasAlpha:(true) isPlanar:(false) colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:(intBPR) bitsPerPixel:(intBPP))
272    #ArtBord
273    ### 初期化 CodeBase
274    refMe's NSGraphicsContext's saveGraphicsState()
275    ###Context
276    set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
277    ###生成された画像でNSGraphicsContext初期化
278    (refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
279    ##色を個別に指定する場合 値は0が暗 1が明
280    set ocidSetColor to (refMe's NSColor's colorWithSRGBRed:(1.0) green:(1.0) blue:(1.0) alpha:(0.0))
281    ocidSetColor's |set|()
282    ###画像生成
283    refMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:(numSmallWidth), height:(numSmallHeight)}})
284    #画像作成終了
285    refMe's NSGraphicsContext's restoreGraphicsState()
286    #合成 リザイスでNSCompositeSourceOver
287    ### 初期化
288    refMe's NSGraphicsContext's saveGraphicsState()
289    ###Context
290    set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
291    ###NSGraphicsContext初期化
292    (refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
293    ####NSCompositeSourceOver
294    set ocidDrawInRect to {origin:{x:(0), y:(0)}, |size|:{width:(numSmallWidth), Hight:(numSmallHeight)}}
295    set ocidFromRect to (refMe's NSZeroRect)
296    # set ocidOption to (refMe's NSCompositeSourceOver)
297    set ocidOption to (refMe's NSCompositingOperationSourceOver)
298    ##  set ocidOption to (refMe's NSCompositeCopy)
299    (ocidReadImageRep's drawInRect:(ocidDrawInRect) fromRect:(ocidFromRect) operation:(ocidOption) fraction:1.0 respectFlipped:true hints:(missing value))
300    #画像作成終了
301    refMe's NSGraphicsContext's restoreGraphicsState()
302    #保存オプション
303    set ocidProperty to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
304    (ocidProperty's setObject:(refMe's NSNumber's numberWithBool:false) forKey:(refMe's NSImageInterlaced))
305    (ocidProperty's setObject:(refMe's NSNumber's numberWithDouble:(1 / 2.2)) forKey:(refMe's NSImageGamma))
306    ##保存
307    set ocidNSInlineData to (ocidArtBoardRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
308    #スモールの保存先
309    set strSmallFileName to (strDateNo & "-" & numCntNo & "_" & numSmallWidth & "x" & numSmallHeight) as text
310    set ocidExportSmallBasePathURL to (ocidExportSmallDirPathURL's URLByAppendingPathComponent:(strSmallFileName) isDirectory:(false))
311    set ocidExportSmallPathURL to (ocidExportSmallBasePathURL's URLByAppendingPathExtension:("png"))
312    
313    set ocidOption to (refMe's NSDataWritingAtomic)
314    set listDone to (ocidNSInlineData's writeToURL:(ocidExportSmallPathURL) options:(ocidOption) |error| :(reference))
315    if (item 1 of listDone) is true then
316      log "【8】保存しました"
317    else if (item 2 of listDone) ≠ (missing value) then
318      log ((item 2 of listDone)'s localizedDescription()) as text
319      return display alert "Automator【8】保存に失敗しました"
320    end if
321    #カウントアップ
322    set numCntNo to numCntNo + 1 as integer
323  end repeat
324  
325  
326  ###########################
327  #【9】OCR作成して移動
328  #カウンター
329  set numCntNo to 1 as integer
330  #収集したファイルを処理
331  repeat with itemURL in ocidExportAutomatorURLArray
332    set ocidOption to (refMe's NSDataReadingMappedIfSafe)
333    set listReadData to (refMe's NSData's alloc()'s initWithContentsOfURL:(itemURL) options:(ocidOption) |error| :(reference))
334    if (item 2 of listReadData) ≠ (missing value) then
335      log (item 2 of listReadStings)'s localizedDescription() as text
336      return display alert "【9】データの読み込みに失敗しました"
337    else
338      log "【9】データの読み込み"
339      set ocidReadData to (item 1 of listReadData)
340    end if
341    #OCRを先に処理
342    #最小フォントサイズ
343    set numMinPt to 8 as integer
344    #####ImageRep画像の高さを取得
345    ##画像に対しての8Ptテキストの比率--> MinimumTextHeightにセットする
346    set ocidImageRep to (refMe's NSBitmapImageRep's imageRepWithData:(ocidReadData))
347    ##ピクセルサイズ取得
348    set numPixelsWidth to ocidReadImageRep's pixelsWide()
349    set numPixelsHeight to ocidReadImageRep's pixelsHigh()
350    set intTextHeight to (numMinPt / numPixelsHeight) as number
351    #####OCR
352    #VNImageRequestHandler's
353    set ocidHandler to (refMe's VNImageRequestHandler's alloc()'s initWithData:(ocidReadData) options:(missing value))
354    #VNRecognizeTextRequest's
355    set ocidRequest to refMe's VNRecognizeTextRequest's alloc()'s init()
356    set ocidOption to (refMe's VNRequestTextRecognitionLevelAccurate)
357    (ocidRequest's setRecognitionLevel:(ocidOption))
358    (ocidRequest's setMinimumTextHeight:(intTextHeight))
359    (ocidRequest's setAutomaticallyDetectsLanguage:(true))
360    (ocidRequest's setRecognitionLanguages:{"en", "ja"})
361    (ocidRequest's setUsesLanguageCorrection:(false))
362    #results
363    (ocidHandler's performRequests:(refMe's NSArray's arrayWithObject:(ocidRequest)) |error| :(reference))
364    set ocidResponseArray to ocidRequest's results()
365    #戻り値を格納するテキスト
366    set ocidFirstOpinionString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
367    set ocidSecondOpinionString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
368    set ocidSaveString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
369    #戻り値の数だけ々
370    repeat with itemArray in ocidResponseArray
371      #候補数指定 1−10 ここでは2種の候補を戻す指定
372      set ocidRecognizedTextArray to (itemArray's topCandidates:(2))
373      set ocidFirstOpinion to ocidRecognizedTextArray's firstObject()
374      set ocidSecondOpinion to ocidRecognizedTextArray's lastObject()
375      (ocidFirstOpinionString's appendString:(ocidFirstOpinion's |string|()))
376      (ocidFirstOpinionString's appendString:("\r"))
377      (ocidSecondOpinionString's appendString:(ocidSecondOpinion's |string|()))
378      (ocidSecondOpinionString's appendString:("\r"))
379    end repeat
380    ##比較して相違点を探すならここで
381    (ocidSaveString's appendString:("-----第1候補\r\r"))
382    (ocidSaveString's appendString:(ocidFirstOpinionString))
383    (ocidSaveString's appendString:("\r\r-----第2候補\r\r"))
384    (ocidSaveString's appendString:(ocidSecondOpinionString))
385    ##
386    set strOCRFileName to (strDateNo & "-" & numCntNo & "_" & numPixelsWidth & "x" & numPixelsHeight) as text
387    set ocidAutomatorExportBasePathURL to (ocidAutomatorExportDirPathURL's URLByAppendingPathComponent:(strOCRFileName) isDirectory:(false))
388    set ocidOcrSaveFilePathURL to (ocidAutomatorExportBasePathURL's URLByAppendingPathExtension:("txt"))
389    #保存
390    set listDone to (ocidSaveString's writeToURL:(ocidOcrSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference))
391    if (item 1 of listDone) is true then
392      log "【9】正常終了"
393    else if (item 1 of listDone) is false then
394      log (item 2 of listDone)'s localizedDescription() as text
395      return display alert " 【9】 OCR保存に失敗しました"
396    end if
397    set ocidImageRep to ""
398    set ocidReadData to ""
399    set ocidMoveFilePathURL to (ocidAutomatorExportBasePathURL's URLByAppendingPathExtension:("png"))
400    set appFileManager to refMe's NSFileManager's defaultManager()
401    set listDone to (appFileManager's moveItemAtURL:(itemURL) toURL:(ocidMoveFilePathURL) |error| :(reference))
402    if (item 1 of listDone) is true then
403      log "【9】移動しました"
404    else if (item 2 of listDone) ≠ (missing value) then
405      log ((item 2 of listDone)'s localizedDescription()) as text
406      return display alert "Automator【9】移動に失敗しました"
407    end if
408    #カウントアップ
409    set numCntNo to numCntNo + 1 as integer
410    
411    
412  end repeat
413  
414  
415end run
416
417
418################################
419# 日付 doGetDateNo()
420################################
421to doGetDateNo(strDateFormat)
422  ####日付情報の取得
423  set ocidDate to current application's NSDate's |date|()
424  ###日付のフォーマットを定義
425  set ocidNSDateFormatter to current application's NSDateFormatter's alloc()'s init()
426  ocidNSDateFormatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
427  ocidNSDateFormatter's setDateFormat:strDateFormat
428  set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate
429  set strDateAndTime to ocidDateAndTime as text
430  return strDateAndTime
431end doGetDateNo
AppleScriptで生成しました

|

[FolderAction]フォルダアクション設定を開く


AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004#
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "AppKit"
009use scripting additions
010property refMe : a reference to current application
011
012set strBundleID to ("com.apple.FolderActionsSetup") as text
013
014set ocidAppURL to doGetBundleID2AppURL(strBundleID)
015set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
016set boolDone to appSharedWorkspace's openURL:(ocidAppURL)
017
018if boolDone is false then
019  tell application id strBundleID to launch
020  tell application id strBundleID to activate
021end if
022
023
024
025
026###################################
027### バンドルIDからアプリケーションURL
028###################################
029to doGetBundleID2AppURL(argBundleID)
030  set strBundleID to argBundleID as text
031  set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
032  ##バンドルIDからアプリケーションのURLを取得
033  set ocidAppBundle to (refMe's NSBundle's bundleWithIdentifier:(strBundleID))
034  if ocidAppBundle ≠ (missing value) then
035    set ocidAppPathURL to ocidAppBundle's bundleURL()
036  else if ocidAppBundle = (missing value) then
037    set ocidAppPathURL to (appSharedWorkspace's URLForApplicationWithBundleIdentifier:(argBundleID))
038  end if
039  ##予備(アプリケーションのURL)
040  if ocidAppPathURL = (missing value) then
041    tell application "Finder"
042      try
043        set aliasAppApth to (application file id strBundleID) as alias
044        set strAppPath to (POSIX path of aliasAppApth) as text
045        set strAppPathStr to refMe's NSString's stringWithString:(strAppPath)
046        set strAppPath to strAppPathStr's stringByStandardizingPath()
047        set ocidAppPathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(strAppPath) isDirectory:true
048      on error
049        return "アプリケーションが見つかりませんでした"
050      end try
051    end tell
052  end if
053  return ocidAppPathURL
054end doGetBundleID2AppURL
AppleScriptで生成しました

|

【自分用】フォルダアクション スクリーンキャプチャーのリサイズ(デュアルモニタに対応)



ダウンロード - 20241029.zip




AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004# 20241029デュアルモニタに対応した
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "AppKit"
009use framework "CoreImage"
010use framework "VisionKit"
011use framework "Vision"
012use scripting additions
013property refMe : a reference to current application
014property refNSNotFound : a reference to 9.22337203685477E+18 + 5807
015################
016##フォルダも作るか?
017property boolMakeDir : false
018
019
020
021on run {argListFilePath}
022  
023  #必要なフォルダがあれば作る
024  set appFileManager to refMe's NSFileManager's defaultManager()
025  #Picturesフォルダ
026  set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
027  set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
028  #テンポラリフォルダ
029  set ocidTempDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/TemporaryItems") isDirectory:(true))
030  #実寸保存先
031  set ocidSaveDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/AutomatorExport") isDirectory:(true))
032  #スモールの保存先
033  set ocidSmallDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/SmallExport") isDirectory:(true))
034  #TIFFの保存先
035  set ocidPostDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/PostImage") isDirectory:(true))
036  
037  if boolMakeDir is true then
038    set ocidAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
039    (ocidAttrDict's setValue:(493) forKey:(refMe's NSFilePosixPermissions))
040    #
041    set listBoolMakeDir to (appFileManager's createDirectoryAtURL:(ocidTempDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference))
042    #
043    set listBoolMakeDir to (appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference))
044    #
045    set listBoolMakeDir to (appFileManager's createDirectoryAtURL:(ocidSmallDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference))
046    #
047    set listBoolMakeDir to (appFileManager's createDirectoryAtURL:(ocidPostDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference))
048  end if
049  
050  ############################
051  #本処理
052  #【1】リネーム
053  #【2】72ppiでAutomatorExportに
054  #【3】半分のサイズをSmallExportに
055  #【4】OCRテキストをAutomatorExport
056  ############################
057  #デュアルモニタに対応するためのカウンタ
058  set numCntNo to (count of argListFilePath) as integer
059  
060  repeat with itemNo from 1 to (numCntNo) by 1
061    
062    set argAliasFilePath to (item itemNo of argListFilePath) as alias
063    ##入力ファイル
064    set strFilePath to (POSIX path of argAliasFilePath) as text
065    
066    set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
067    set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
068    set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
069    set ocidFileName to ocidFilePath's lastPathComponent()
070    set ocidExtensionName to ocidFilePathURL's pathExtension()
071    ###########################
072    #【1】リネーム
073    ###########################
074    
075    set strDateNo to doGetDateNo("yyyyMMdd-hhmmss")
076    set strDateNo to (strDateNo & "-" & itemNo)
077    
078    set ocidMoveTmpBaseFilePathURL to (ocidTempDirPathURL's URLByAppendingPathComponent:(strDateNo) isDirectory:(false))
079    #拡張子
080    set ocidTmpFilePathURL to (ocidMoveTmpBaseFilePathURL's URLByAppendingPathExtension:(ocidExtensionName))
081    #移動
082    set listDone to (appFileManager's moveItemAtURL:(ocidFilePathURL) toURL:(ocidTmpFilePathURL) |error| :(reference))
083    if (item 1 of listDone) is true then
084      log "【1】移動しました"
085    else if (item 2 of listDone) ≠ (missing value) then
086      log ((item 2 of listDone)'s localizedDescription()) as text
087      return display alert "Automatorファイルの移動に失敗しました"
088    end if
089    
090    ###########################
091    #【2】72ppiでAutomatorExportに
092    ###########################
093    #####データ読み込み
094    set ocidOption to (refMe's NSDataReadingMappedIfSafe)
095    set listReadData to (refMe's NSData's alloc()'s initWithContentsOfURL:(ocidTmpFilePathURL) options:(ocidOption) |error| :(reference))
096    if (item 2 of listReadData) ≠ (missing value) then
097      log (item 2 of listReadStings)'s localizedDescription() as text
098      return "【4】データの読み込みに失敗しました"
099    else
100      set ocidReadData to (item 1 of listReadData)
101    end if
102    
103    ##NSIMAGEに読み込む
104    set ocidReadImage to (refMe's NSImage's alloc()'s initWithData:(ocidReadData))
105    #サイズPT
106    set recordSize to ocidReadImage's |size|()
107    set numWidthPtSize to (recordSize's width) as number
108    set numHeightPtSize to (recordSize's height) as number
109    ##BitMapRepに変換
110    set ocidReadImageRepArray to ocidReadImage's representations()
111    set ocidReadImageRep to ocidReadImageRepArray's firstObject()
112    ##ピクセルサイズ取得
113    set numPixelsWidth to ocidReadImageRep's pixelsWide()
114    set numPixelsHeight to ocidReadImageRep's pixelsHigh()
115    #解像度の比率
116    set numMag to (numPixelsWidth / numWidthPtSize) as integer
117    #解像度と同じなら
118    if numMag = 1 then
119      set strSaveFileName to (strDateNo & "_" & numPixelsWidth & "x" & numPixelsHeight) as text
120    else
121      set numWidthPtSize to (numWidthPtSize) as integer
122      set numHeightPtSize to (height of recordSize) as integer
123      set strSaveFileName to (strDateNo & "_" & numWidthPtSize & "x" & numHeightPtSize & "@" & numMag) as text
124    end if
125    #原寸として移動する
126    set ocidSaveBasePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName) isDirectory:(false))
127    set ocidSaveFilePathURL to (ocidSaveBasePathURL's URLByAppendingPathExtension:(ocidExtensionName))
128    set listDone to (appFileManager's moveItemAtURL:(ocidTmpFilePathURL) toURL:(ocidSaveFilePathURL) |error| :(reference))
129    if (item 1 of listDone) is true then
130      log "【2】移動しました"
131    else if (item 2 of listDone) ≠ (missing value) then
132      log ((item 2 of listDone)'s localizedDescription()) as text
133      return display alert "Automator【2】移動に失敗しました"
134    end if
135    ###########################
136    #【3】半分のサイズをSmallExportに
137    ###########################
138    #まず72ppiにする
139    set ocidPixelsSize to refMe's NSMakeSize(numPixelsWidth, numPixelsHeight)
140    (ocidReadImageRep's setSize:(ocidPixelsSize))
141    #半分サイズ(数値の丸めで1ピクセルの誤差を容認)
142    set numSmallWidth to (numPixelsWidth / 2) as integer
143    set numSmallHeight to (numPixelsHeight / 2) as integer
144    set ocidSmallSize to refMe's NSMakeSize(numSmallWidth, numSmallHeight)
145    set ocidSmallRect to refMe's NSMakeRect(0, 0, numSmallWidth, numSmallHeight)
146    #出力用イメージ NSBitmapImageRep
147    # samplesPerPixel
148    set intSPP to 4 as integer
149    # bitsPerSample
150    set intBPS to 8 as integer
151    # bytesPerRow
152    set intBPR to (numSmallWidth * intSPP) as integer
153    # bitsPerPixel
154    set intBPP to 32 as integer
155    # RGB系のカラースペース
156    set ocidColorSpaceName to refMe's NSCalibratedRGBColorSpace
157    # アルファあり
158    set ocidBitmapFormat to refMe's NSAlphaFirstBitmapFormat
159    ##出力ピクセルサイズのブランクイメージ
160    set ocidArtBoardRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numSmallWidth) pixelsHigh:(numSmallHeight) bitsPerSample:(intBPS) samplesPerPixel:(intSPP) hasAlpha:(true) isPlanar:(false) colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:(intBPR) bitsPerPixel:(intBPP))
161    ###########################
162    #ArtBord
163    ### 初期化 CodeBase
164    refMe's NSGraphicsContext's saveGraphicsState()
165    ###Context
166    set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
167    ###生成された画像でNSGraphicsContext初期化
168    (refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
169    ##色を個別に指定する場合 値は0が暗 1が明
170    set ocidSetColor to (refMe's NSColor's colorWithSRGBRed:(1.0) green:(1.0) blue:(1.0) alpha:(0.0))
171    ocidSetColor's |set|()
172    ###画像生成
173    refMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:(numSmallWidth), height:(numSmallHeight)}})
174    #画像作成終了
175    refMe's NSGraphicsContext's restoreGraphicsState()
176    
177    ###########################
178    #合成 リザイスでNSCompositeSourceOver
179    ### 初期化
180    refMe's NSGraphicsContext's saveGraphicsState()
181    ###Context
182    set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
183    ###NSGraphicsContext初期化
184    (refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
185    ####NSCompositeSourceOver
186    set ocidDrawInRect to {origin:{x:(0), y:(0)}, |size|:{width:(numSmallWidth), Hight:(numSmallHeight)}}
187    set ocidFromRect to (refMe's NSZeroRect)
188    # set ocidOption to (refMe's NSCompositeSourceOver)
189    set ocidOption to (refMe's NSCompositingOperationSourceOver)
190    ##  set ocidOption to (refMe's NSCompositeCopy)
191    (ocidReadImageRep's drawInRect:(ocidDrawInRect) fromRect:(ocidFromRect) operation:(ocidOption) fraction:1.0 respectFlipped:true hints:(missing value))
192    #画像作成終了
193    refMe's NSGraphicsContext's restoreGraphicsState()
194    
195    ###########################
196    #保存オプション
197    set ocidProperty to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
198    (ocidProperty's setObject:(refMe's NSNumber's numberWithBool:false) forKey:(refMe's NSImageInterlaced))
199    (ocidProperty's setObject:(refMe's NSNumber's numberWithDouble:(1 / 2.2)) forKey:(refMe's NSImageGamma))
200    ##保存
201    set ocidNSInlineData to (ocidArtBoardRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
202    #スモールの保存先
203    set strSmallFileName to (strDateNo & "_" & numPixelsWidth & "x" & numSmallHeight) as text
204    set ocidSmallBasePathURL to (ocidSmallDirPathURL's URLByAppendingPathComponent:(strSmallFileName))
205    set ocidSmallFilePathURL to (ocidSmallBasePathURL's URLByAppendingPathExtension:(ocidExtensionName))
206    # set boolDone to (ocidNSInlineData's writeToURL:(ocidSmallFilePathURL) atomically:true)
207    set ocidOption to (refMe's NSDataWritingAtomic)
208    set listDone to (ocidNSInlineData's writeToURL:(ocidSmallFilePathURL) options:(ocidOption) |error| :(reference))
209    if (item 1 of listDone) is true then
210      log "【3】保存しました"
211    else if (item 2 of listDone) ≠ (missing value) then
212      log ((item 2 of listDone)'s localizedDescription()) as text
213      return display alert "Automator【3】保存に失敗しました"
214    end if
215    
216    ###########################
217    #【4】OCRテキストをAutomatorExport
218    ###########################
219    set numMinPt to 8 as integer
220    
221    #####ImageRep画像の高さを取得
222    ##画像に対しての8Ptテキストの比率--> MinimumTextHeightにセットする
223    set ocidImageRep to (refMe's NSBitmapImageRep's imageRepWithData:(ocidReadData))
224    set numImageHeight to ocidImageRep's pixelsHigh()
225    set intTextHeight to (numMinPt / numImageHeight) as number
226    #####OCR
227    #VNImageRequestHandler's
228    set ocidHandler to (refMe's VNImageRequestHandler's alloc()'s initWithData:(ocidReadData) options:(missing value))
229    #VNRecognizeTextRequest's
230    set ocidRequest to refMe's VNRecognizeTextRequest's alloc()'s init()
231    set ocidOption to (refMe's VNRequestTextRecognitionLevelAccurate)
232    (ocidRequest's setRecognitionLevel:(ocidOption))
233    (ocidRequest's setMinimumTextHeight:(intTextHeight))
234    (ocidRequest's setAutomaticallyDetectsLanguage:(true))
235    (ocidRequest's setRecognitionLanguages:{"en", "ja"})
236    (ocidRequest's setUsesLanguageCorrection:(false))
237    #results
238    (ocidHandler's performRequests:(refMe's NSArray's arrayWithObject:(ocidRequest)) |error| :(reference))
239    set ocidResponseArray to ocidRequest's results()
240    #戻り値を格納するテキスト
241    set ocidFirstOpinionString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
242    set ocidSecondOpinionString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
243    set ocidSaveString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
244    #戻り値の数だけ々
245    repeat with itemArray in ocidResponseArray
246      #候補数指定 1−10 ここでは2種の候補を戻す指定
247      set ocidRecognizedTextArray to (itemArray's topCandidates:(2))
248      set ocidFirstOpinion to ocidRecognizedTextArray's firstObject()
249      set ocidSecondOpinion to ocidRecognizedTextArray's lastObject()
250      (ocidFirstOpinionString's appendString:(ocidFirstOpinion's |string|()))
251      (ocidFirstOpinionString's appendString:("\r"))
252      (ocidSecondOpinionString's appendString:(ocidSecondOpinion's |string|()))
253      (ocidSecondOpinionString's appendString:("\r"))
254    end repeat
255    ##比較して相違点を探すならここで
256    (ocidSaveString's appendString:("-----第1候補\r\r"))
257    (ocidSaveString's appendString:(ocidFirstOpinionString))
258    (ocidSaveString's appendString:("\r\r-----第2候補\r\r"))
259    (ocidSaveString's appendString:(ocidSecondOpinionString))
260    ###保存
261    set ocidOcrBaseFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName) isDirectory:(false))
262    #拡張子
263    set ocidOcrFilePathURL to (ocidOcrBaseFilePathURL's URLByAppendingPathExtension:("txt"))
264    #保存
265    set listDone to (ocidSaveString's writeToURL:(ocidOcrFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference))
266    if (item 1 of listDone) is true then
267      log "【4】正常終了"
268    else if (item 1 of listDone) is false then
269      log (item 2 of listDone)'s localizedDescription() as text
270      return display alert " 【4】 保存に失敗しました"
271    end if
272    
273    set ocidSaveString to ""
274    set ocidReadData to ""
275    set ocidNSInlineData to ""
276    set ocidReadImageRepArray to ""
277    set ocidReadImageRep to ""
278    
279  end repeat
280end run
281
282
283################################
284# 日付 doGetDateNo()
285################################
286to doGetDateNo(strDateFormat)
287  ####日付情報の取得
288  set ocidDate to current application's NSDate's |date|()
289  ###日付のフォーマットを定義
290  set ocidNSDateFormatter to current application's NSDateFormatter's alloc()'s init()
291  ocidNSDateFormatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
292  ocidNSDateFormatter's setDateFormat:strDateFormat
293  set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate
294  set strDateAndTime to ocidDateAndTime as text
295  return strDateAndTime
296end doGetDateNo
AppleScriptで生成しました

|

[Automater]スクリーンキャプチャーと同時に処理を行う(OCRをテキストで保存)


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#com.cocolog-nifty.quicktimer.icefloe
#Automater用です
#保存先フォルダ等に指定があります(このままでは動作しないよ的な)
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use framework "CoreImage"
use framework "VisionKit"
use framework "Vision"
use scripting additions
property refMe : a reference to current application
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807
################
##フォルダも作るか?
property boolMakeDir : true



#on run {argListFilePath}
on run
  #必要なフォルダがあれば作る
  set appFileManager to refMe's NSFileManager's defaultManager()
  #Picturesフォルダ
  set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSPicturesDirectory) inDomains:(refMe's NSUserDomainMask))
  set ocidPicturesDirPathURL to ocidURLsArray's firstObject()
  #テンポラリフォルダ
  set ocidTempDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/TemporaryItems") isDirectory:(true))
  #実寸保存先
  set ocidSaveDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/AutomatorExport") isDirectory:(true))
  #スモールの保存先
  set ocidSmallDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/SmallExport") isDirectory:(true))
  #TIFFの保存先
  set ocidPostDirPathURL to (ocidPicturesDirPathURL's URLByAppendingPathComponent:("ScreenCapture/PostImage") isDirectory:(true))
  
  if boolMakeDir is true then
    set ocidAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidAttrDict's setValue:(493) forKey:(refMe's NSFilePosixPermissions))
    #
    set listBoolMakeDir to (appFileManager's createDirectoryAtURL:(ocidTempDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference))
    #
    set listBoolMakeDir to (appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference))
    #
    set listBoolMakeDir to (appFileManager's createDirectoryAtURL:(ocidSmallDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference))
    #
    set listBoolMakeDir to (appFileManager's createDirectoryAtURL:(ocidPostDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference))
  end if
  
  ############################
  #本処理
  #【1】リネーム
  #【2】72ppiでAutomatorExportに
  #【3】半分のサイズをSmallExportに
  #【4】OCRテキストをAutomatorExport
  ############################
  # repeat with argAliasFilePath in argListFilePath
  ##入力ファイル
  # set strFilePath to (POSIX path of argAliasFilePath) as text
  set strFilePath to ("~/Pictures/ScreenCapture/ScreenCapture/screen.png") as text
  
  set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
  set ocidFileName to ocidFilePath's lastPathComponent()
  set ocidExtensionName to ocidFilePathURL's pathExtension()
  ###########################
  #【1】リネーム
  ###########################
  #日付時間ファイル名
  set strDateNo to doGetDateNo("yyyyMMdd-hhmmss")
  set ocidMoveTmpBaseFilePathURL to (ocidTempDirPathURL's URLByAppendingPathComponent:(strDateNo) isDirectory:(false))
  #拡張子
  set ocidTmpFilePathURL to (ocidMoveTmpBaseFilePathURL's URLByAppendingPathExtension:(ocidExtensionName))
  #移動
  set listDone to (appFileManager's moveItemAtURL:(ocidFilePathURL) toURL:(ocidTmpFilePathURL) |error|:(reference))
  if (item 1 of listDone) is true then
log "【1】移動しました"
  else if (item 2 of listDone) ≠ (missing value) then
log ((item 2 of listDone)'s localizedDescription()) as text
return display alert "Automatorファイルの移動に失敗しました"
  end if
  ###########################
  #【2】72ppiでAutomatorExportに
  ###########################
  #####データ読み込み
  set ocidOption to (refMe's NSDataReadingMappedIfSafe)
  set listReadData to (refMe's NSData's alloc()'s initWithContentsOfURL:(ocidTmpFilePathURL) options:(ocidOption) |error|:(reference))
  if (item 2 of listReadData) ≠ (missing value) then
log (item 2 of listReadStings)'s localizedDescription() as text
return "【4】データの読み込みに失敗しました"
  else
    set ocidReadData to (item 1 of listReadData)
  end if
  
  ##NSIMAGEに読み込む
  set ocidReadImage to (refMe's NSImage's alloc()'s initWithData:(ocidReadData))
  #サイズPT
  set recordSize to ocidReadImage's |size|()
  set numWidthPtSize to (recordSize's width) as number
  set numHeightPtSize to (recordSize's height) as number
  ##BitMapRepに変換
  set ocidReadImageRepArray to ocidReadImage's representations()
  set ocidReadImageRep to ocidReadImageRepArray's firstObject()
  ##ピクセルサイズ取得
  set numPixelsWidth to ocidReadImageRep's pixelsWide()
  set numPixelsHeight to ocidReadImageRep's pixelsHigh()
  #解像度の比率
  set numMag to (numPixelsWidth / numWidthPtSize) as integer
  #解像度と同じなら
  if numMag = 1 then
    set strSaveFileName to (strDateNo & "-" & numPixelsWidth & "x" & numPixelsHeight) as text
  else
    set numWidthPtSize to (numWidthPtSize) as integer
    set numHeightPtSize to (height of recordSize) as integer
    set strSaveFileName to (strDateNo & "-" & numWidthPtSize & "x" & numHeightPtSize & "@" & numMag) as text
  end if
  #原寸として移動する
  set ocidSaveBasePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName) isDirectory:(false))
  set ocidSaveFilePathURL to (ocidSaveBasePathURL's URLByAppendingPathExtension:(ocidExtensionName))
  set listDone to (appFileManager's moveItemAtURL:(ocidTmpFilePathURL) toURL:(ocidSaveFilePathURL) |error|:(reference))
  if (item 1 of listDone) is true then
log "【2】移動しました"
  else if (item 2 of listDone) ≠ (missing value) then
log ((item 2 of listDone)'s localizedDescription()) as text
return display alert "Automator【2】移動に失敗しました"
  end if
  ###########################
  #【3】半分のサイズをSmallExportに
  ###########################
  #まず72ppiにする
  set ocidPixelsSize to refMe's NSMakeSize(numPixelsWidth, numPixelsHeight)
(ocidReadImageRep's setSize:(ocidPixelsSize))
  #半分サイズ(数値の丸めで1ピクセルの誤差を容認)
  set numSmallWidth to (numPixelsWidth / 2) as integer
  set numSmallHeight to (numPixelsHeight / 2) as integer
  set ocidSmallSize to refMe's NSMakeSize(numSmallWidth, numSmallHeight)
  set ocidSmallRect to refMe's NSMakeRect(0, 0, numSmallWidth, numSmallHeight)
  #出力用イメージ NSBitmapImageRep
  # samplesPerPixel
  set intSPP to 4 as integer
  # bitsPerSample
  set intBPS to 8 as integer
  # bytesPerRow
  set intBPR to (numSmallWidth * intSPP) as integer
  # bitsPerPixel
  set intBPP to 32 as integer
  # RGB系のカラースペース
  set ocidColorSpaceName to refMe's NSCalibratedRGBColorSpace
  # アルファあり
  set ocidBitmapFormat to refMe's NSAlphaFirstBitmapFormat
  ##出力ピクセルサイズのブランクイメージ
  set ocidArtBoardRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numSmallWidth) pixelsHigh:(numSmallHeight) bitsPerSample:(intBPS) samplesPerPixel:(intSPP) hasAlpha:(true) isPlanar:(false) colorSpaceName:(ocidColorSpaceName) bitmapFormat:(ocidBitmapFormat) bytesPerRow:(intBPR) bitsPerPixel:(intBPP))
  ###########################
  #ArtBord
  ### 初期化 CodeBase
refMe's NSGraphicsContext's saveGraphicsState()
  ###Context
  set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
  ###生成された画像でNSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
  ##色を個別に指定する場合 値は0が暗 1が明
  set ocidSetColor to (refMe's NSColor's colorWithSRGBRed:(1.0) green:(1.0) blue:(1.0) alpha:(0.0))
ocidSetColor's |set|()
  ###画像生成
refMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:(numSmallWidth), height:(numSmallHeight)}})
  #画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
  
  ###########################
  #合成 リザイスでNSCompositeSourceOver
  ### 初期化
refMe's NSGraphicsContext's saveGraphicsState()
  ###Context
  set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep))
  ###NSGraphicsContext初期化
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
  ####NSCompositeSourceOver
  set ocidDrawInRect to {origin:{x:(0), y:(0)}, |size|:{width:(numSmallWidth), Hight:(numSmallHeight)}}
  set ocidFromRect to (refMe's NSZeroRect)
  # set ocidOption to (refMe's NSCompositeSourceOver)
  set ocidOption to (refMe's NSCompositingOperationSourceOver)
  ## set ocidOption to (refMe's NSCompositeCopy)
(ocidReadImageRep's drawInRect:(ocidDrawInRect) fromRect:(ocidFromRect) operation:(ocidOption) fraction:1.0 respectFlipped:true hints:(missing value))
  #画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
  
  ###########################
  #保存オプション
  set ocidProperty to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidProperty's setObject:(refMe's NSNumber's numberWithBool:false) forKey:(refMe's NSImageInterlaced))
(ocidProperty's setObject:(refMe's NSNumber's numberWithDouble:(1 / 2.2)) forKey:(refMe's NSImageGamma))
  ##保存
  set ocidNSInlineData to (ocidArtBoardRep's representationUsingType:(refMe's NSBitmapImageFileTypePNG) |properties|:(ocidProperty))
  #スモールの保存先
  set strSmallFileName to (strDateNo & "-" & numPixelsWidth & "x" & numSmallHeight) as text
  set ocidSmallBasePathURL to (ocidSmallDirPathURL's URLByAppendingPathComponent:(strSmallFileName))
  set ocidSmallFilePathURL to (ocidSmallBasePathURL's URLByAppendingPathExtension:(ocidExtensionName))
  # set boolDone to (ocidNSInlineData's writeToURL:(ocidSmallFilePathURL) atomically:true)
  set ocidOption to (refMe's NSDataWritingAtomic)
  set listDone to (ocidNSInlineData's writeToURL:(ocidSmallFilePathURL) options:(ocidOption) |error|:(reference))
  if (item 1 of listDone) is true then
log "【3】保存しました"
  else if (item 2 of listDone) ≠ (missing value) then
log ((item 2 of listDone)'s localizedDescription()) as text
return display alert "Automator【3】保存に失敗しました"
  end if
  
  ###########################
  #【4】OCRテキストをAutomatorExport
  ###########################
  set numMinPt to 8 as integer
  
  #####ImageRep画像の高さを取得
  ##画像に対しての8Ptテキストの比率--> MinimumTextHeightにセットする
  set ocidImageRep to (refMe's NSBitmapImageRep's imageRepWithData:(ocidReadData))
  set numImageHeight to ocidImageRep's pixelsHigh()
  set intTextHeight to (numMinPt / numImageHeight) as number
  #####OCR
  #VNImageRequestHandler's
  set ocidHandler to (refMe's VNImageRequestHandler's alloc()'s initWithData:(ocidReadData) options:(missing value))
  #VNRecognizeTextRequest's
  set ocidRequest to refMe's VNRecognizeTextRequest's alloc()'s init()
  set ocidOption to (refMe's VNRequestTextRecognitionLevelAccurate)
(ocidRequest's setRecognitionLevel:(ocidOption))
(ocidRequest's setMinimumTextHeight:(intTextHeight))
(ocidRequest's setAutomaticallyDetectsLanguage:(true))
(ocidRequest's setRecognitionLanguages:{"en", "ja"})
(ocidRequest's setUsesLanguageCorrection:(false))
  #results
(ocidHandler's performRequests:(refMe's NSArray's arrayWithObject:(ocidRequest)) |error|:(reference))
  set ocidResponseArray to ocidRequest's results()
  #戻り値を格納するテキスト
  set ocidFirstOpinionString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
  set ocidSecondOpinionString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
  set ocidSaveString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
  #戻り値の数だけ々
  repeat with itemArray in ocidResponseArray
    #候補数指定 1−10 ここでは2種の候補を戻す指定
    set ocidRecognizedTextArray to (itemArray's topCandidates:(2))
    set ocidFirstOpinion to ocidRecognizedTextArray's firstObject()
    set ocidSecondOpinion to ocidRecognizedTextArray's lastObject()
(ocidFirstOpinionString's appendString:(ocidFirstOpinion's |string|()))
(ocidFirstOpinionString's appendString:("\n"))
(ocidSecondOpinionString's appendString:(ocidSecondOpinion's |string|()))
(ocidSecondOpinionString's appendString:("\n"))
  end repeat
  ##比較して相違点を探すならここで
(ocidSaveString's appendString:("-----第1候補\n\n"))
(ocidSaveString's appendString:(ocidFirstOpinionString))
(ocidSaveString's appendString:("\n\n-----第2候補\n\n"))
(ocidSaveString's appendString:(ocidSecondOpinionString))
  ###保存
  set ocidOcrBaseFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName) isDirectory:(false))
  #拡張子
  set ocidOcrFilePathURL to (ocidOcrBaseFilePathURL's URLByAppendingPathExtension:("txt"))
  #保存
  set listDone to (ocidSaveString's writeToURL:(ocidOcrFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference))
  if (item 1 of listDone) is true then
log "【4】正常終了"
  else if (item 1 of listDone) is false then
log (item 2 of listDone)'s localizedDescription() as text
return display alert " 【4】 保存に失敗しました"
  end if
  
  set ocidSaveString to ""
  set ocidReadData to ""
  set ocidNSInlineData to ""
  set ocidReadImageRepArray to ""
  set ocidReadImageRep to ""
  
  # end repeat
end run


################################
# 日付 doGetDateNo()
################################
to doGetDateNo(strDateFormat)
  ####日付情報の取得
  set ocidDate to current application's NSDate's |date|()
  ###日付のフォーマットを定義
  set ocidNSDateFormatter to current application's NSDateFormatter's alloc()'s init()
ocidNSDateFormatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
ocidNSDateFormatter's setDateFormat:strDateFormat
  set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate
  set strDateAndTime to ocidDateAndTime as text
return strDateAndTime
end doGetDateNo

|

[フォルダアクション]ダウンロードしたURLをファイルコメント入れておく

フォルダアクション用
ZIPファイルの解凍時の処理は考え中


【スクリプトエディタで開く】


on run {argAliasFilePath}
  ###受け取ったファイルパスをエリアスとUNIXパスにしておく
  set strFilePath to (POSIX path of argAliasFilePath) as text
  set aliasFilePath to argAliasFilePath as alias
  ###コマンド整形
  set strCommandText to "/usr/bin/mdls -name \"kMDItemWhereFroms\"  \"" & strFilePath & "\""
  ###コマンド実行
  set strResponse to (do shell script strCommandText) as text
  ###ダブルクオトでリスト化
  set AppleScript's text item delimiters to "\""
  set listResponse to every text item of strResponse
  set AppleScript's text item delimiters to ""
  ###コメントに入れるテキスト初期化
  set strCommentText to "" as text
  ###リストの数だけ繰り返し
  repeat with itemResponse in listResponse
    set strItemResponse to itemResponse as text
    if strItemResponse starts with "http" then
      set strCommentText to strCommentText & strItemResponse & "\r"
    end if
  end repeat
  ########すでに登録されているコメント
  tell application "Finder"
    set strNowComment to (comment of aliasFilePath) as text
  end tell
  ######すでにコメントがある場合は追加する
  if strNowComment is not "" then
    set strCommentText to (strNowComment & "\r" & strCommentText) as text
  end if
  #####コメントをセットする
  tell application "Finder"
    set comment of file aliasFilePath to strCommentText
  end tell
  return
end run

|

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat AddOn Acrobat Annotation Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat JS Acrobat Manifest Acrobat Menu Acrobat Open Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat Python Acrobat Reader Acrobat Reader Localized Acrobat Reference Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin Support Admin System Information Admin Tools Admin Users Admin Volumes Admin XProtect Adobe Adobe Bridge Adobe FDKO Adobe Fonts Adobe Reference Adobe RemoteUpdateManager AppKit Apple AppleScript AppleScript do shell script AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript System Events AppleScript System Events Plist AppleScript Video Applications AppStore Archive Attributes Automator BackUp Barcode Barcode Decode Barcode QR Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome CIImage CityCode CloudStorage Color com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time defaults delimiters Desktop Device Diff Disk Dock DropBox Droplet eMail Encode % Encode Decode Encode HTML Entity Encode UTF8 Error EXIFData ffmpeg File File Name Finder Firefox Folder FolderAction Fonts Fonts ATS Fonts Python Foxit GIF github Guide HTML Icon Illustrator Image Events Image2PDF ImageOptim Input Dictionary iPhone iWork Javascript Jedit Json Label Language Leading Zero List locationd LRC lsappinfo m3u8 Mail MakePDF Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Microsoft Fonts Microsoft Office Mouse Music NetWork Notes NSArray NSArray Sort NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSColor NSColorList NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMetadataItem NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth OneDrive PDF PDF Pymupdf PDFAnnotation PDFAnnotationWidget PDFContext PDFDisplayBox PDFDocumentPermissions PDFImageRep PDFKit PDFnUP PDFOutline PDFView perl Photoshop PlistBuddy pluginkit plutil postalcode PostScript prefPane Preview Python QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver SF Symbols character id SF Symbols Entity sips Skype Slack Sound Spotlight sqlite SRT StandardAdditions Swift System Settings TCC TemporaryItems Terminal Text Text CSV Text MD Text TSV TextEdit Tools Translate Trash Twitter Typography UI Unit Conversion UTType valueForKeyPath Video VisionKit Visual Studio Code VMware Fusion Wacom webarchive webp Wifi Windows XML XML EPUB XML HTML XML LSSharedFileList XML OPML XML Plist XML RSS XML savedSearch XML SVG XML TTML XML webloc XML xmllint XML XMP YouTube zoom