现在,我的代码为我提供了具有正确缩放高度和宽度的图像,但使用了原始图像的顶部。我希望它使用图像的中心。但是我不知道如何为imagecopyresampled计算dst_y的值来做到这一点。谁能帮我解决:-)
<?php
function ReSize ($source,$destination,$dest_imagex,$dest_imagey,$quality) {
$source_image = imagecreatefromjpeg($source);
// Get dimensions of the original image
$source_imagex = imagesx($source_image);
$source_imagey = imagesy($source_image);
$after_width = $dest_imagex;
//get the reduced width
$reduced_width = ($source_imagex - $after_width);
//now convert the reduced width to a percentage and round it to 2 decimal places
$reduced_radio = round(($reduced_width / $source_imagex) * 100, 2);
//ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places.
$reduced_height = round(($source_imagey / 100) * $reduced_radio, 2);
//reduce the calculated height from the original height
$after_height = $source_imagey - $reduced_height;
$dst_y = 0; // The calculation I cannot figure out.....
$dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);
imagecopyresampled($dest_image, $source_image, 0, $dst_y, 0, 0, $after_width, $after_height, $source_imagex, $source_imagey);
$cache_folder = 'images/cache/';
$new_image = $cache_folder . rawurlencode($destination). '_' . $dest_imagex . 'x' . $dest_imagey . '.jpg';
imagejpeg($dest_image, $new_image,$quality);
echo $new_image;
}
?>
答案 0 :(得分:0)
假设您要调整CSS“覆盖”类型的大小,有两种选择:
首先找到源和目标比率:
$dest_ratio = $dest_imagex / $dest_imagey;
$source_ratio = $source_imagex / $source_imagey;
如果源比例大于目标比例,则意味着您需要水平配合比例,否则需要垂直配合比例。
imagecopyresampled(
$dest_image,
$source_image,
0,
0,
0,
($source_imagey - ($source_imagex * $dest_ratio)) / 2,
$dest_imagex,
$dest_imagex * $source_ratio,
$source_imagex,
$source_imagey
);
imagecopyresampled(
$dest_image,
$source_image,
0,
0,
($source_imagex - ($source_imagey / $dest_ratio)) / 2,
0,
$dest_imagey / $source_ratio,
$dest_imagey,
$source_imagex,
$source_imagey
);
function crop($source, $dest, $dest_imagex, $dest_imagey, $quality)
{
$source_image = imagecreatefromjpeg($source);
// Get dimensions of the original image
$source_imagex = imagesx($source_image);
$source_imagey = imagesy($source_image);
$source_ratio = $source_imagey / $source_imagex;
$dest_ratio = $dest_imagey / $dest_imagex;
$dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);
imagefill($dest_image, 0, 0, imagecolorallocate($dest_image, 255, 0, 0));
if ($dest_ratio >= $source_ratio) {
imagecopyresampled(
$dest_image,
$source_image,
0,
0,
($source_imagex - ($source_imagey / $dest_ratio)) / 2,
0,
$dest_imagey / $source_ratio,
$dest_imagey,
$source_imagex,
$source_imagey
);
} else {
imagecopyresampled(
$dest_image,
$source_image,
0,
0,
0,
($source_imagey - ($source_imagex * $dest_ratio)) / 2,
$dest_imagex,
$dest_imagex * $source_ratio,
$source_imagex,
$source_imagey
);
}
imagejpeg($dest_image, $dest, $quality);
}
crop("image1.jpg", "image1_resized.jpg", 100, 100, 100);