Reputation: 79477
I load a PNG image in a QPixmap/QImage and I want to crop it. Is there a function that does that in Qt, or how should I do it otherwise?
Upvotes: 45
Views: 42316
Reputation: 8221
You can use QPixmap::copy:
QRect rect(10, 20, 30, 40);
QPixmap original('image.png');
QPixmap cropped = original.copy(rect);
There is also QImage::copy:
QRect rect(10, 20, 30, 40);
QImage original('image.png');
QImage cropped = original.copy(rect);
Upvotes: 59
Reputation: 291
Use QImage instead of QPixmap:
QImage image("initial_image.jpg");
QImage copy ;
copy = image.copy( 0, 0, 128, 128);
copy.save("cropped_image.jpg");
This code will save a file cropped to upper left corner 128x128px.
Upvotes: 29
Reputation: 3412
Just use of the QPixmap's copy() functions.
This text is result of reading the first comment on your quiestion:
Sometimes it is better to wrap around an image. That is to have an image that is part of another image or in other words points to a part of another image. This is way the wrapped image does not require additional memory, except for its header. You can display or save the wrapped image without worries. The downside is that the original image must remain valid until you use the wrapped image, also if you are drawing in the wrapped image it will affect the source.
Upvotes: 2
Reputation: 20028
Since you use QPixmap, you can use its copy method and supply it with a QRect to perform the actual crop.
Upvotes: 4