How do I fit an image to an exact size? I don't want to distort the image, I need to fit it on a black background and it needs to be centered whether that's side to side or top to bottom. They're originally large images that I need to get down to 25px wide by 32px high.
Right now I'm simply checking for width and height and figure out which needs to be resized:
InitializeMagick(*argv);
Image img(imgFilename);
// Check image dimensions
if (img.columns() > img.rows()) {
// wide image!
if (img.columns() > 25) {
img.resize(Magick::Geometry("25x"));
}
} else {
// tall image!
if (img.rows() > 32) {
img.resize(Magick::Geometry("x32"));
}
}
I have to believe there's a simpler/better way of doing this while also fitting it to a 25px wide by 32px tall canvas with the image in the center. How do I do that?
By the way, I realize there's a problem with the above code ... if img.columns() == img.rows() it always goes to the second case and sizes the image to 32 high which isn't correct as that will cause img.columns() to also go to 32, which is outside of the required 25 pixels. This is something I'm assuming an image fit would take care of. I just don't know how.
I believe evaluating the image columns & rows might be unnecessary. Magick::Geometry supports additional qualifier like (
>
) "only resize if image is bigger" and (^
) "crop/fill to size". You should be able to use a combination of qualifiers to resize images, if needed, and extent the image to fit.Of course, you may also apply the qualifiers in the
extent
method. I would suggest experimenting with them using theconvert
utility, and example documents.