How to programmatically crop an image from a non-rectangular shape?

I want to crop a rectangular image into a non-rectangular shape. I understand that if you take it literally, it is impossible. I want the result to be an image X, cropped to shape Y, on a transparent background.

Say, for example, that I want to photograph the Idaho flag and crop it to the state of Idaho. I assume I will do something like this:

  • Create an image with opaque pixels for an Idaho shape, transparent pixels everywhere.
  • Read and save a bitmap of this Idaho image
  • For each opaque pixel location in the Idaho state image, copy the corresponding pixel from the Idaho state flag image and place it on a blank transparent canvas.

Step 1 will obviously be done manually, but the rest will be done programmatically. I think I have the right idea in general, but I don’t know how I will approach the specifics. Can someone point me in the right direction?

Regarding the implementation technology, I'm a PHP guy, so using gdLibrary or something that works with PHP will probably be the best way for me.

+5
source share
3 answers
+2

- - ( 1) ( 0) . , . 0, 0, , 1.

, . ( ) .

, , , . , Windows MaskBlt.

+2

In php using ImageMagick is probably best:

$source = IMagick("sourcefile");
$mask = IMagick("maskfile");
$mask->adaptiveResizeImage($source->getImageWidth(), $source->getImageHeight(), true);
$source->compositeImage($mask, imagick::COMPOSITE_MULTIPLY, 0, 0);
$source->writeImage("newfile");
$source->clear();
$source->destroy();

the source file should be the source image of your choice, maskfile should be the mask file that correctly configured the alpha channel for the shape you need.

+1
source

All Articles