這裏是一個函數香港專業教育學院剛剛完成對力一個確切的像素大小 - 我不能保證它100%,但我測試了很多選項,並獲得完美的結果,迄今爲止,它給出了最接近的結果imo。首先,通過計算比率來調整源圖像和指定大小之間的最小差異。然後修剪掉多餘的像素。我已經補償了奇數,負值等。到目前爲止我已經有了很好的結果。請讓或我知道,如果香港專業教育學院錯過的東西,如果它打破以某種方式:
PHP:
// set source/export paths and pixel sizes for final sizes
$src="path/to/source.jpg";
$exp="path/to/output.jpg";
$crop_w=300;
$crop_h=200;
$size = getimagesize("$src");
//check image sizes
if(($size[0] < $crop_w) || ($size[1] < $crop_h)){
echo 'Image not big enough to crop';
exit();
}
//get differential ratios of image vs crop sizes -
//smaller ratio must be resized
$ratio_w = $size[0]/$crop_w;
$ratio_h = $size[1]/$crop_h;
//square or landscape - shave sides
if($ratio_w >= $ratio_h){
//resize width/shave top&bottom
exec("convert $src -resize x".$crop_h." $exp ");
$size = getimagesize("$exp");
$diff=abs($crop_w-$size[1]);
//dividing 1 by 2 will leave a zero on round down - just force resize
if($diff < 2){
// skip shave - diff too small
exec('convert $exp -resize '.$crop_h.'X! $exp ');
}
else{
//divide difference by 2 for shave amount
$shave = round($diff/2,0,PHP_ROUND_HALF_DOWN); //halve & round difference down to avoid cropping smaller
exec('convert '.$exp.' -shave '.$shave.'x0 '.$exp.' '); //shave sides
//odd $diff leave a rounded down pixel - force height resize
if($diff%2 !==0){//if $diff was not divisible by two then 1 pixel is left from round down
exec('convert '.$exp.' -resize '.$crop_w.'x! '.$exp.' ');
}
}
}
//portrait - shave height
else{
//resize width/shave top&bottom
exec("convert $src -resize ".$crop_w."x $exp ");
$size = getimagesize("$exp");
$diff=abs($crop_h-$size[1]);
//dividing 1 by 2 will leave a zero on round down - just force resize
if($diff < 2){
exec('convert $exp -resize x'.$crop_h.'! $exp ');
}
else{
//divide difference by 2 for shave amount
$shave = round($diff/2,0,PHP_ROUND_HALF_DOWN); //halve & round difference down to avoid cropping smaller
exec('convert '.$exp.' -shave 0x'.$shave.' '.$exp.' '); //shave sides
//odd $diff leave a rounded down pixel - force height resize
if($diff%2 !==0){//if $diff was not divisible by two then 1 pixel is left from round down
exec('convert '.$exp.' -resize x'.$crop_h.'! '.$exp.' ');
}
}
}
隨意使用/發表評論。 Php 5.4 <,Imagemagick 6.8.8.1,Windows xampp。