Cropping an image (destructively)


#1

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:


#2

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:


#3

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.


#4

Thanks for the help!


#5

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


#6

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)

cheers


#7

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