Cropping an image (destructively)

Hey, I have an array of icons tiled in a single image. To get a specific icon, I call getClippedImage(rect…), however if I wish to modify the icon afterwards I will modify the original image.

Do I need to duplicate the original array of icons (the large image) for each individual icon I want to modify? That seems wasteful. It would be good to be able to destructively crop the original, or deep copy a subsection.

…Or hopefully I’ve missed an easy way to do it :slight_smile:

Good question.

I was about to just say do this:

Image newImage = oldImage.getClippedImage (whatever).duplicateIfShared();

…but in fact if the original image has nothing else using it, then that won’t actually create a copy, it’ll just keep the clipped one.

If you’re doing this, it should always work:

…because in that case there are definitely multiple references to the image, but it doesn’t feel right.

This is actually a good argument for me adding a clone() method to the Image class, which I’ll do, but in the meantime you could do it like this:

BTW there would be no advantage in me adding a destructive method to clip an image, since internally it’d just do almost exactly the same thing as my suggested code above.

Thanks for the help!

(FYI I’ve added a createCopy() method now)

There seems to be a bug in copying sub-images.

SubsectionPixelData::clone has the line

g.drawImageAt (Image (this), -area.getX(), -area.getY());

Which draws the image at a wrong position.
It would work well either if “this” is changed to “image” or if the position is changed to (0,0).

(using latest tip)


Ah, yes - sorry, that should be (0, 0). Thanks!