crop image using imagevent

how do i crop the bottom half of an image using image events?, since the script below cuts both edges:

tell application "Image Events"

launch

set this_image to open "~/Desktop/screen.jpg"

copy dimensions of this_image to {W, H}

crop this_image to dimensions {W - 210, H - 250}

save this_image

close this_image

end tell

MacBook Pro

Posted on Nov 15, 2015 12:15 PM

Reply
9 replies

Nov 15, 2015 9:10 PM in response to rupaln

I'm certainly not a scripting expert but that file has information that is useful. Looking at that site I would try using the following commands:


set the vertical_crop to 0.5 -- 50%

set the horizontal_crop to 0


-- get dimensions of the image

copy dimensions of this_image to {W, H}

-- perform action

crop this_image to dimensions {W - (W * horizontal_crop), H - (H * vertical_crop)}

Dec 12, 2015 9:22 AM in response to rupaln

Hi rupaln,


It's not possible with Image Events. Its crop command always trims equally from the top and bottom (or left and right sides) of the loaded image, so it can't be used to crop off the top or bottom half.


Instead you'll need to use a scriptable image editing program such as Adobe Photoshop (expensiveware) or GraphicConverter (shareware, or available from the App Store). I don't have PS, but the following scripts work with GraphicConverter:


To crop off the top half of an open image:


tell application "GraphicConverter 9"


activate

set full_size to get image dimension of window 1

set W to item 1 of full_size

set H to item 2 of full_size

set half_H to round (H / 2)

set selection of window 1 to {0, half_H, W, H}


crop selectionwindow 1

end tell



To crop off the bottom half of an open image:


tell application "GraphicConverter 9"


activate

set full_size to get image dimension of window 1

set W to item 1 of full_size

set H to item 2 of full_size

set half_H to round (H / 2)

set selection of window 1 to {0, 0, W, half_H}


crop selection window 1

end tell

The downside to this is that the images have to be open on screen in GraphicConverter, so if you're batch converting a lot of images you'll get continuous screen activity while it's working.


Be aware also that if your script is written so that it opens, crops, saves and closes a number of images, this will be a permanent change, so you may want to work on copies rather than originals.


Hope this helps,


H

Dec 12, 2015 12:43 PM in response to rupaln

You could also use Preview.app.


set theImageFile to POSIX file "/Users/pierre/Desktop/Test.JPG" as alias-- as an example


tell application "Preview"

activate

set theImage to opentheImageFile

display dialog "How many pixels do you want to remove from the bottom of the picture." default answer "50" buttons {"Cancel", "Crop"} default button 2 with icon 1

set N to text returned of result as integer

set N1 to N div 10

set N2 to N mod 10

tell application "System Events"

keystroke "a" using {command down} -- select all

repeat N1 times

key code 126 using {shift down, command down} -- 10 pixels at a time

end repeat

repeat N2 times

key code 126 using {command down} -- 1 pixel at a time

end repeat

keystroke "k" using {command down} -- resize

end tell

closetheImagesavingyes

end tell

Dec 12, 2015 6:44 PM in response to rupaln

Hello


You might try the following python/pyobjc script. It will crop the lower half of given jpeg image and overwrite the original file(s).



#!/usr/bin/python # coding: utf-8 # # file: # crop_lower_half.py # # function: # crop the lower half of jpeg image and overwrite the original file # # usage e.g.: # ./crop_lower_half.py *.jpg # # version: # 0.12 # # written by Hiroto, 2015-12 # import sys from Quartz.CoreGraphics import * from Quartz.ImageIO import * # from CoreFoundation import * for f in [ a.decode('utf-8') for a in sys.argv[1:] ]: url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, f, kCFURLPOSIXPathStyle, False) isrc = CGImageSourceCreateWithURL(url, {}) img = CGImageSourceCreateImageAtIndex(isrc, 0, {}) if not img: sys.stderr.write('failed to get image from file: %s\n' % f) continue w = CGImageGetWidth(img) h = CGImageGetHeight(img) img1 = CGImageCreateWithImageInRect(img, CGRectMake(0.0, 0.0, w, h / 2)) idst = CGImageDestinationCreateWithURL(url, 'public.jpeg', 1, None) CGImageDestinationAddImage(idst, img1, {}) b = CGImageDestinationFinalize(idst) if not b: sys.stderr.write('failed to write output file: %s\n' % f)




Here's an AppleScript wrapper if it helps.



set aa to choose file of type {"public.jpeg"} with multiple selections allowed set args to "" repeat with a in aa set args to args & space & a's POSIX path's quoted form end repeat do shell script "/usr/bin/python <<'EOF' - " & args & " # coding: utf-8 # # file: # crop_lower_half.py # # function: # crop the lower half of jpeg image and overwrite the original file # # usage e.g.: # ./crop_lower_half.py *.jpg # # version: # 0.12 # # written by Hiroto, 2015-12 # import sys from Quartz.CoreGraphics import * from Quartz.ImageIO import * # from CoreFoundation import * for f in [ a.decode('utf-8') for a in sys.argv[1:] ]: url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, f, kCFURLPOSIXPathStyle, False) isrc = CGImageSourceCreateWithURL(url, {}) img = CGImageSourceCreateImageAtIndex(isrc, 0, {}) if not img: sys.stderr.write('failed to get image from file: %s\\n' % f) continue w = CGImageGetWidth(img) h = CGImageGetHeight(img) img1 = CGImageCreateWithImageInRect(img, CGRectMake(0.0, 0.0, w, h / 2)) idst = CGImageDestinationCreateWithURL(url, 'public.jpeg', 1, None) CGImageDestinationAddImage(idst, img1, {}) b = CGImageDestinationFinalize(idst) if not b: sys.stderr.write('failed to write output file: %s\\n' % f) EOF"




Briefly tested with pyobjc 2.2b3 and python 2.6.1 under OS X 10.6.8 but no warranties. Scripts will overwrite the original files. Please make sure you have backupus before running the script.


Good luck,

H

Dec 13, 2015 11:04 AM in response to Hiroto

It's also possible to do something similar with Quartz Composer: I've just created a CG image filter composition that crops images in the same way as these Python scripts and can be incorporated into an Automator service, drag-and-drop application or folder action.


A bit more elegant than my original suggestion, but a bit more complex to set up.


H

Dec 13, 2015 3:17 PM in response to HD

Hello HD,


Yes. Core Image filter is fun and CICrop will work for current problem. 🙂



rupaln,


Here's revised script which has corrected error string encoding and refined error handling a little.



#!/usr/bin/python # coding: utf-8 # # file: # crop_lower_half.py # # function: # crop the lower half of jpeg image and overwrite the original file # # usage e.g.: # ./crop_lower_half.py *.jpg # # version: # v0.13 # - refined error handling and corrected error string encoding # # written by Hiroto, 2015-12 # import sys from Quartz.CoreGraphics import * from Quartz.ImageIO import * # from CoreFoundation import * err = 0 for f in [ a.decode('utf-8') for a in sys.argv[1:] ]: url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, f, kCFURLPOSIXPathStyle, False) isrc = CGImageSourceCreateWithURL(url, {}) if not isrc: sys.stderr.write('failed to create image source from file: %s\n' % f.encode('utf-8')) err = 1 continue img = CGImageSourceCreateImageAtIndex(isrc, 0, {}) if not img: sys.stderr.write('failed to get image from file: %s\n' % f.encode('utf-8')) err = 1 continue w = CGImageGetWidth(img) h = CGImageGetHeight(img) img1 = CGImageCreateWithImageInRect(img, CGRectMake(0.0, 0.0, w, h / 2)) idst = CGImageDestinationCreateWithURL(url, 'public.jpeg', 1, None) CGImageDestinationAddImage(idst, img1, {}) b = CGImageDestinationFinalize(idst) if not b: sys.stderr.write('failed to write output file: %s\n' % f.encode('utf-8')) err = 1 sys.exit(err)




And its AppleScript wrapper.



set aa to choose file of type {"public.jpeg"} with multiple selections allowed crop_lower_half(aa) on crop_lower_half(aa) (* list aa : alias list of jpeg files *) set args to "" repeat with a in (aa as list) set args to args & space & (a as alias)'s POSIX path's quoted form end repeat do shell script "/usr/bin/python <<'EOF' - " & args & " # coding: utf-8 # # file: # crop_lower_half.py # # function: # crop the lower half of jpeg image and overwrite the original file # # usage e.g.: # ./crop_lower_half.py *.jpg # # version: # v0.13 # - refined error handling and corrected error string encoding # # written by Hiroto, 2015-12 import sys from Quartz.CoreGraphics import * from Quartz.ImageIO import * # from CoreFoundation import * err = 0 for f in [ a.decode('utf-8') for a in sys.argv[1:] ]: url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, f, kCFURLPOSIXPathStyle, False) isrc = CGImageSourceCreateWithURL(url, {}) if not isrc: sys.stderr.write('failed to create image source from file: %s\\n' % f.encode('utf-8')) err = 1 continue img = CGImageSourceCreateImageAtIndex(isrc, 0, {}) if not img: sys.stderr.write('failed to get image from file: %s\\n' % f.encode('utf-8')) err = 1 continue w = CGImageGetWidth(img) h = CGImageGetHeight(img) img1 = CGImageCreateWithImageInRect(img, CGRectMake(0.0, 0.0, w, h / 2)) idst = CGImageDestinationCreateWithURL(url, 'public.jpeg', 1, None) CGImageDestinationAddImage(idst, img1, {}) b = CGImageDestinationFinalize(idst) if not b: sys.stderr.write('failed to write output file: %s\\n' % f.encode('utf-8')) err = 1 sys.exit(err) EOF" end crop_lower_half



All the best,

H

Dec 13, 2015 5:14 PM in response to rupaln

Hi rupaln. If you don't mind using a third-party solution, another option is to use the free command-line image tool ImageMagick. ImageMagick's crop operator is by default relative to the top-left corner of an image. As an example, to crop 20 pixels off the bottom of a 400x320 pixel PNG image with the filename "image.png" on the Desktop, and output a new cropped PNG file with the filename "bottom_cropped.png" in the same location, use the following command in Terminal:


convert ~/Desktop/image.png -crop 400x300+0+0 +repage ~/Desktop/bottom_cropped.png


For an AppleScript, assuming ImageMagick's convert binary is located in /opt/ImageMagick/bin/, use the following command in Script Editor:


do shell script "/opt/ImageMagick/bin/convert ~/Desktop/image.png -crop 400x300+0+0 +repage ~/Desktop/bottom_cropped.png"


If you want to overwrite the original image using the same filename, use the mogrify command instead of convert:


mogrify -crop 400x300+0+0 +repage ~/Desktop/image.png


The same command in Script Editor:


do shell script "/opt/ImageMagick/bin/mogrify -crop 400x300+0+0 +repage ~/Desktop/image.png"


To get the image dimensions you can use ImageMagick's identify command in Terminal:


identify -ping -format '%w %h' ~/Desktop/image.png


The same command in Script Editor:


do shell script "/opt/ImageMagick/bin/identify -ping -format '%w %h' ~/Desktop/image.png"


More info:


http://www.imagemagick.org/Usage/crop/

http://www.imagemagick.org/script/convert.php

http://www.imagemagick.org/script/mogrify.php

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

crop image using imagevent

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.