使用 php imagick 调整大小
我正在上传图像并将它们的大小调整为 300x200 像素,
我正在使用 imagick 扩展,特别是adaptiveResizeImage() 函数。
使用 bestfit 上传时,图像两侧有很多空白(取决于纵向或横向)。
我宁愿它做的是调整大小以填充整个区域(没有空白)并裁剪较长的长度(高度或宽度),即我宁愿丢失一些图像而不是有空白。
有没有一种简单的方法可以使用 imagick 扩展来做到这一点?
编辑:我设法做到了我需要的,但必须有更好的方法
header('Content-type: image/jpeg');
// target sizes
$target_width = 300 ;
$target_height = 100 ;
// create new image
$image = new Imagick('test.jpg');
// get current size and calculate diffences from target sizes
$size = $image->getImageGeometry();
$size['width_diff'] = $target_width/$size['width'] ;
$size['height_diff'] = $target_height/$size['height'] ;
// resize by smallest size
if($size['width_diff']>=$size['height_diff'])
{
$width = $target_width ;
$height = $size['height']*$size['width_diff'] ;
}
else
{
$width = $size['width']*$size['height_diff'] ;
$height = $target_height ;
}
// get offsets
$x = ($width-$target_width)/2 ;
$y = ($height-$target_height)/2 ;
// resize and offset image
$image->adaptiveResizeImage($width, $height) ;
$image->extentImage($target_width, $target_height,-$x,-$y);
// output and clean up
echo $image ;
$image->clear();
$image->destroy();
I am uploading images and resizing them to 300x200 pixels
i'm using the imagick extension and specifically the adaptiveResizeImage() function.
when uploaded using bestfit there is a lot of whitespace on the sides of the image (depending on portrait or landscape).
what i'd rather it did was resize to fill the entire area (no whitespace) and crop the longer length (height or width), ie i'd rather lose some image than have whitespace.
is there an easy way to do this with the imagick extension?
EDIT: I managed to do what i needed, but there has to be a better way
header('Content-type: image/jpeg');
// target sizes
$target_width = 300 ;
$target_height = 100 ;
// create new image
$image = new Imagick('test.jpg');
// get current size and calculate diffences from target sizes
$size = $image->getImageGeometry();
$size['width_diff'] = $target_width/$size['width'] ;
$size['height_diff'] = $target_height/$size['height'] ;
// resize by smallest size
if($size['width_diff']>=$size['height_diff'])
{
$width = $target_width ;
$height = $size['height']*$size['width_diff'] ;
}
else
{
$width = $size['width']*$size['height_diff'] ;
$height = $target_height ;
}
// get offsets
$x = ($width-$target_width)/2 ;
$y = ($height-$target_height)/2 ;
// resize and offset image
$image->adaptiveResizeImage($width, $height) ;
$image->extentImage($target_width, $target_height,-$x,-$y);
// output and clean up
echo $image ;
$image->clear();
$image->destroy();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许您可以查看 ImageMagick 教程中的 extent 标志。
快速浏览一下,似乎等效的 PHP 是 Imagick::ExtentImage
但还没有在 php 中使用过它。
Maybe you can take a look at the extent flag in the ImageMagick tutorial.
From a quick look it seems the equivalent PHP would be Imagick::ExtentImage
but have not used it from php.