如何在Ubuntu上永久缩放imagemagick++图像

How to permanently scale an ImageMagick++ image on Ubuntu?

本文关键字:缩放 imagemagick++ 图像 Ubuntu      更新时间:2023-10-16

我有一个imagemagick++图像,我想将其缩放到我喜欢的任何宽度和高度,然后我想访问这个新缩放图像的像素。

我希望缩放操作永久地改变图像。到目前为止,有四个imagemagick++方法听起来像是可以实现这种缩放操作:resize()、sample()、scale()和transform(),但我唯一能做的是sample()。

问题是,当我调用tMyImage.sample()然后读取像素值时,图像只缩放到我传递给它的高度,然后根据原始宽高比设置宽度。

这是我使用的代码:

Magick::Image tMyIMage(iOriginalWidth, iOriginalHeight, "BGRA", Magick::CharPixel, (void *)pSourceData);
try { tImage.sample(Magick::Geometry(200, 50, 0, 0)); }
catch { Magick::Exception &eException)
{
    // This never happens...
}
tImage.modifyImage();
size_t nNewWidth = tImage.columns();
size_t nNewHeight = tImage.rows();
// At this point I would expect that nNewWidth is 200 and nNewHeight is 50
// Instead, nNewHeight is 50 but nNewWidth is scaled according to the original aspect ratio
// Note here that tImage.baseColumns() and tImage.baseRows() both return 0
tImage.type(Magick::TrueColorType);
const Magick::PixelPacket *pPixels = tImage.getConstPixels(0, 0, nNewWidth, nNewHeight);
// Here I would expect that pPixels points to pixel data of a 200x50 pixel image

我是新的imagemagick++,所以我确信我一定是做错了什么。任何帮助都非常感谢!谢谢!

我发现了缩放不工作的原因;显然,imagemagick++的默认设置是,如果最终的宽高比会发生变化,则不会采用您正在使用的确切尺寸在创建几何图形时,必须显式地告诉imagemagick++使用精确的尺寸:

char szGeometry[64];
memset(&(szGeometry[0]), 0, sizeof(szGeometry));
snprintf(szGeometry, sizeof(szGeometry) - 1, "%ix%i!", iWidth, iHeight);
Magick::Image tScaled(iOriginalWidth, iOriginalHeight, "BGRA", Magick::CharPixel, (void *)pSourceData);
try { tScaled.sample(Magick::Geometry(szGeometry)); }
catch (Magick::Exception &eException)
{
    ...
}