Skip to content

Instantly share code, notes, and snippets.

@timburks
Created March 1, 2011 06:56
Show Gist options
  • Save timburks/848739 to your computer and use it in GitHub Desktop.
Save timburks/848739 to your computer and use it in GitHub Desktop.
AppKit image cropping
(import Cocoa)
(set data (NSData dataWithContentsOfFile:"iphone-screenshot.png"))
(set image ((NSImage alloc) initWithData:data))
(set oldsize (image size))
(cond ((eq oldsize '(640 960))
(set newsize '(640 920)))
;; add more as needed
(else (puts "unknown size")
(exit)))
(set oldrect (append '(0 0) newsize))
(set newrect (append '(0 0) newsize))
(set croppedImage ((NSImage alloc) initWithSize:newsize))
(croppedImage lockFocus)
(image drawInRect:newrect
fromRect:oldrect
operation:NSCompositeSourceOver
fraction:1.0)
(croppedImage unlockFocus)
(set croppedData (croppedImage TIFFRepresentation))
(set croppedImageRep (NSBitmapImageRep imageRepWithData:croppedData))
;; write png
(set croppedPNGData (croppedImageRep representationUsingType:NSPNGFileType
properties:nil))
(croppedPNGData writeToFile:"cropped.png" atomically:YES)
;; write jpeg
(if NO
(set croppedJPEGData (croppedImageRep representationUsingType:NSJPEGFileType
properties:(dict NSImageCompressionFactor 0.9)))
(croppedJPEGData writeToFile:"cropped.jpg" atomically:YES))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment