本文介绍了PHP适合任何尺寸的图像,以16:9的宽高比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
中午好,
我目前正在尝试了解如何裁剪纵横比为16:9的服务器上已加载的图像.为了更好地理解,如果我有4:3的图像,则必须剪切顶部和底部的图像部分以使其适合16:9的比例.
I'm currently trying to understand how i can crop image already loaded on server with 16:9 aspect ratio.For better understandig, if I have 4:3 image i have to cut top and bottom image portions to fit it into 16:9 ratio.
谢谢.
推荐答案
我举了以下代码示例: http://myrusakov.ru/php-crop-image.html 然后按照我的需要更改代码:
I took this code example: http://myrusakov.ru/php-crop-image.htmland changed the code according to my needs in this way:
function crop_image($image) {
//$x_o и $y_o - Output image top left angle coordinates on input image
//$w_o и h_o - Width and height of output image
list($w_i, $h_i, $type) = getimagesize($image); // Return the size and image type (number)
//calculating 16:9 ratio
$w_o = $w_i;
$h_o = 9 * $w_o / 16;
//if output height is longer then width
if ($h_i < $h_o) {
$h_o = $h_i;
$w_o = 16 * $h_o / 9;
}
$x_o = $w_i - $w_o;
$y_o = $h_i - $h_o;
$types = array("", "gif", "jpeg", "png"); // Array with image types
$ext = $types[$type]; // If you know image type, "code" of image type, get type name
if ($ext) {
$func = 'imagecreatefrom'.$ext; // Get the function name for the type, in the way to create image
$img_i = $func($image); // Creating the descriptor for input image
} else {
echo 'Incorrect image'; // Showing an error, if the image type is unsupported
return false;
}
if ($x_o + $w_o > $w_i) $w_o = $w_i - $x_o; // If width of output image is bigger then input image (considering x_o), reduce it
if ($y_o + $h_o > $h_i) $h_o = $h_i - $y_o; // If height of output image is bigger then input image (considering y_o), reduce it
$img_o = imagecreatetruecolor($w_o, $h_o); // Creating descriptor for input image
imagecopy($img_o, $img_i, 0, 0, $x_o/2, $y_o/2, $w_o, $h_o); // Move part of image from input to output
$func = 'image'.$ext; // Function that allows to save the result
return $func($img_o, $image); // Overwrite input image with output on server, return action's result
}
欢迎您提出任何想法或意见.
You're welcome for any idea or opinion on that.
这篇关于PHP适合任何尺寸的图像,以16:9的宽高比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!