/*TODO 图片裁剪*/
function img_cutting($file_old, $file_new, $h, $w) {
$image = $file_old; // 原图
$dir = 'xxxxxx'; //新地址
if (!is_dir($dir)) {
mkdir($dir, 0777, true);
}
$imgstream = file_get_contents($image);
$im = imagecreatefromstring($imgstream);
$x = imagesx($im); //获取图片的宽
$y = imagesy($im); //获取图片的高
// 缩略后的大小
$xx = $h;
$yy = $w;
if ($x > $y) {
//图片宽大于高
$sx = abs(($y - $x) / 2);
$sy = 0;
$thumbw = $y;
$thumbh = $y;
} else {
//图片高大于等于宽
$sy = abs(($x - $y) / 2.5);
$sx = 0;
$thumbw = $x;
$thumbh = $x;
}
$img_info = getimagesize($file_old);
if (end($img_info) == 'image/png') {
$img = imagecreatefrompng($file_old);
imagesavealpha($img, true); //这里很重要;
if (function_exists("imagecreatetruecolor")) {
$dim = imagecreatetruecolor($yy, $xx); // 创建目标图gd2
} else {
$dim = imagecreate($yy, $xx); // 创建目标图gd1
}
imagealphablending($dim, false); //这里很重要,意思是不合并颜色,直接用$img图像颜色替换,包括透明色;
imagesavealpha($dim, true); //这里很重要,意思是不要丢了$thumb图像的透明色;
imageCopyreSampled($dim, $im, 0, 0, $sx, $sy, $yy, $xx, $thumbw, $thumbh);
return imagepng($dim, $file_new);
} else if(end($img_info) != 'image/gif') {
if (function_exists("imagecreatetruecolor")) {
$dim = imagecreatetruecolor($yy, $xx); // 创建目标图gd2
} else {
$dim = imagecreate($yy, $xx); // 创建目标图gd1
}
imageCopyreSampled($dim, $im, 0, 0, $sx, $sy, $yy, $xx, $thumbw, $thumbh);
return imagejpeg($dim, $file_new, 100);
}
}
发表评论