我已经制作了两个GIF来解释我想要做什么.灰色边框是我追求的尺寸(700*525).他们是这个问题的底部.
我希望所有大于给定宽度和高度的图像缩小到边界(从中心),然后裁剪边缘.以下是我将这些代码放在一起的一些代码:
if ($heightofimage => 700 && $widthofimage => 525){
if ($heightofimage > $widthofimage){
$widthofimage = 525;
$heightofimage = //scaled height.
//crop height to 700.
}
if ($heightofimage < $widthofimage){
$widthofimage = //scaled width.
$heightofimage = 700;
//crop width to 525.
}
}else{
echo "image too small";
}
Run Code Online (Sandbox Code Playgroud)
以下是一些可视化解释我想要实现的内容的GIF:
GIF 1:这里的图像比例是在太多了x方向

GIF 2:这里的图像比例是在太多了y方向

所以我用你的方法用PHP(点击这里用php做你自己的测试),然后将它与原始照片进行比较,因为你可以看到有很大的不同!:
http://tragicclothing.co.uk/video%20images/test/yo.jpg

下面的代码应该做你想要的.我没有对它进行过广泛的测试,但它似乎对我制作的几张测试图像起作用.在心灵的背后有一个令人尴尬的疑问,我的数学错误,但现在已经很晚了,我看不出任何明显的东西.
编辑:它已经足够琐碎我再次经历并发现了这个错误,即作物不在图像的中间.代码替换为工作版本.
简而言之:将此作为起点,而不是生产就绪代码!
<?php
// set image size constraints.
$target_w = 525;
$target_h = 700;
// get image.
$in = imagecreatefrompng('<path to your>.png');
// get image dimensions.
$w = imagesx($in);
$h = imagesy($in);
if ($w >= $target_w && $h >= $target_h) {
// get scales.
$x_scale = ($w / $target_w);
$y_scale = ($h / $target_h);
// create new image.
$out = imagecreatetruecolor($target_w, $target_h);
$new_w = $target_w;
$new_h = $target_h;
$src_x = 0;
$src_y = 0;
// compare scales to ensure we crop whichever is smaller: top/bottom or
// left/right.
if ($x_scale > $y_scale) {
$new_w = $w / $y_scale;
// see description of $src_y, below.
$src_x = (($new_w - $target_w) / 2) * $y_scale;
} else {
$new_h = $h / $x_scale;
// a bit tricky. crop is done by specifying coordinates to copy from in
// source image. so calculate how much to remove from new image and
// then scale that up to original. result is out by ~1px but good enough.
$src_y = (($new_h - $target_h) / 2) * $x_scale;
}
// given the right inputs, this takes care of crop and resize and gives
// back the new image. note that imagecopyresized() is possibly quicker, but
// imagecopyresampled() gives better quality.
imagecopyresampled($out, $in, 0, 0, $src_x, $src_y, $new_w, $new_h, $w, $h);
// output to browser.
header('Content-Type: image/png');
imagepng($out);
exit;
} else {
echo 'image too small';
}
?>
Run Code Online (Sandbox Code Playgroud)