2008-05-11

Crop Images with GdiPlusX

Cropping an image is super simple using GdiplusX

Prerequisites
Visual FoxPro 9 and the GdiplusX library from VFPX at GitHub 


Please make sure that you have the latest version!

The cropping is done by the fuction "Clone()" from the xfcBitmap class. All we need is to pass a xfcRectangle object containing the X, Y, Width and Height of the desired image to be cropped.

Original image



Top Left


Center


Bottom Right


Run the code below, selecting any image, and you will see the image cropped in three ways: the top-left part of the image, the bottom-right part, and the center.


LOCAL lcsource, lnwidth, lnheight
m.lcsource = GETPICT()
IF EMPTY(m.lcsource)
 RETURN
ENDIF

DO LOCFILE("system.app")

WITH _SCREEN.SYSTEM.drawing

 * load image to gdiplusx
 LOCAL lobmp AS xfcbitmap
 m.lobmp    = .BITMAP.fromfile(m.lcsource)
 m.lnwidth  = m.lobmp.WIDTH
 m.lnheight = m.lobmp.HEIGHT

 * crop image
 LOCAL locropped AS xfcbitmap

 * crop top-left
 LOCAL lorect AS xfcrectangle
 m.lorect = .rectangle.new(0, 0, m.lnwidth / 2, m.lnheight / 2)
 m.locropped = m.lobmp.CLONE(m.lorect)
 m.locropped.SAVE("d:\Tools\crop-topleft.png", .imaging.imageformat.png)
 RUN /N explorer.EXE d:\Tools\crop-topleft.png

 * crop bottom-right
 * now, the rectangle region will be created inside the clone function
 m.locropped = m.lobmp.CLONE(.rectangle.new(m.lnwidth / 2, m.lnheight / 2, m.lnwidth / 2, m.lnheight / 2))
 m.locropped.SAVE("d:\Tools\crop-bottomright.png", .imaging.imageformat.png)
 RUN /N explorer.EXE d:\Tools\crop-bottomright.png

 * crop center
 m.locropped = m.lobmp.CLONE(.rectangle.new(m.lnwidth / 4, m.lnheight / 4, m.lnwidth / 2, m.lnheight / 2))
 m.locropped.SAVE("d:\Tools\crop-center.png", .imaging.imageformat.png)
 RUN /N explorer.EXE d:\Tools\crop-CENTER.png

ENDWITH
RETURN

3 comments:

  1. This cropping method can really help me. Thank you for this nice post Cesar!
    BTW, how to resize the images ?
    Hi,
    I'm glad it was helpful to you. At the link below there are some techniques for resizeng. Enjoy !
    VFP IMAGING : Resizing images with GdiPlus X
    http://weblogs.foxite.com/vfpimaging/archive/2006/12/29/3068.aspx

    ReplyDelete
  2. How can i convert from rectangular image to rounded image ?

    ReplyDelete
  3. Hi. Thank you for this article. I was wondering if I can automatically crop white spaces?


    Thanks

    ReplyDelete