Efficiently crop and copy an image?

Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like "How do I use ImageMagick to create drop shadows?".
Post Reply
anotherprogrammer123
Posts: 36
Joined: 2010-02-21T18:02:40-07:00
Authentication code: 8675308

Efficiently crop and copy an image?

Post by anotherprogrammer123 »

Hi,

I am using Magick++ and was wondering what is the most efficient way to crop a Magick::Image and store this cropped region in a new Magick::Image.
The code I am currently using is below, but I think it is inefficient because the whole image is copied:

Code: Select all

Magick::Image img("myImage.jpg");
Magick::Geometry cropRegion(0, 0, 100, 100);
//We need to use a temporary object because "crop" modifies the original image
Magick::Image temp = img;
temp.crop(cropRegion);
temp.display();
Thanks in advance.
User avatar
magick
Site Admin
Posts: 11064
Joined: 2003-05-31T11:32:55-07:00

Re: Efficiently crop and copy an image?

Post by magick »

The most efficient crop would be:
  • Magick::Image img("myImage.jpg[100x100+0+0]");
anotherprogrammer123
Posts: 36
Joined: 2010-02-21T18:02:40-07:00
Authentication code: 8675308

Re: Efficiently crop and copy an image?

Post by anotherprogrammer123 »

Thanks for the quick response! However, it will not work in my particular case. Sorry for not being more clear in the first post.

The image I am using will have crop called to it potentially many times. Also, I will not have access to the file name.
The function is embedded inside another class as such:

Code: Select all

Magick::Image image::crop(int width, int length)
{
    Magick::Geometry cropRegion(0, 0, width, length);
    //We need to use a temporary object because "crop" modifies the original image
    Magick::Image temp = this->img;
    temp.crop(cropRegion);
    return temp;
}
anotherprogrammer123
Posts: 36
Joined: 2010-02-21T18:02:40-07:00
Authentication code: 8675308

Re: Efficiently crop and copy an image?

Post by anotherprogrammer123 »

*bump*
User avatar
magick
Site Admin
Posts: 11064
Joined: 2003-05-31T11:32:55-07:00

Re: Efficiently crop and copy an image?

Post by magick »

The crop() method is the proper way to crop an image. ImageMagick uses reference counted image objects so the source image pixels are not replicated to a new pixel cache. Instead the crop image is created and the source pixels are copied to the crop image pixel container. We suspect you cannot get any more efficient than that other than perhaps using some other API.
anotherprogrammer123
Posts: 36
Joined: 2010-02-21T18:02:40-07:00
Authentication code: 8675308

Re: Efficiently crop and copy an image?

Post by anotherprogrammer123 »

Okay, thanks for the responses!
Post Reply