Screenshot with AppleScriptObjC

(Jonas Whale) #1

Is there an AppleScriptObjC method to make a screenshot of a specified area?
(I mean specify the area in the script, not by dragging the mouse…)

For now, I’m using the shell command screencapture and crop the resulting image in Photoshop.

(Shane Stanley) #2

No, it’s all C-based APIs.

(Jonas Whale) #3

Bad news!

Thanks anyway!

(Shane Stanley) #4

You can still do the cropping without involving Photoshop.

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set aRect to current application's NSMakeRect(100, 100, 300, 100) -- x, y, width, height, with y zero at bottom
my cropImage:"/users/shane/Desktop/Screen Shot 2017-11-29 at 9.43.38 pm.png" usingRect:aRect

on cropImage:posixPath usingRect:aRect
	set anNSString to current application's NSString's stringWithString:posixPath
	set newPath to anNSString's stringByDeletingPathExtension()
	set newPath to (newPath's stringByAppendingString:"-2")'s stringByAppendingPathExtension:"jpg"
	set theImage to current application's NSImage's alloc()'s initWithContentsOfFile:posixPath
	set theWidth to current application's NSWidth(aRect)
	set theHeight to current application's NSHeight(aRect)
	set newImage to current application's NSImage's alloc()'s initWithSize:{theWidth, theHeight} -- make new blank image
	-- draw from original to new
	newImage's lockFocus()
	theImage's drawAtPoint:{0, 0} fromRect:aRect operation:(current application's NSCompositeSourceOver) fraction:1.0
	newImage's unlockFocus()
	set theData to newImage's TIFFRepresentation() -- get bitmap as data
	set newRep to current application's NSBitmapImageRep's imageRepWithData:theData -- make bitmap from data
	set theData to (newRep's representationUsingType:(current application's NSJPEGFileType) |properties|:{NSImageCompressionFactor:0.8, NSImageProgressive:false}) -- turn the bitmap into JPEG data
	(theData's writeToFile:newPath atomically:true) -- write it to disk	
end cropImageAt:usingRect:

(Jonas Whale) #5

I was precisely trying to figure out how to do this!

You’re reading my thoughts!

(Jean Christophe Helary) #6

Seems to me imagemagick would be a better tool for that.