本文提供一个PHP图片裁切成正方形的函数,因为实现起来比较简单,所以只做了简单的注释。
/**
* 图片设置相同的宽和高
* @param string $image
* @return number
*/
static function square($image) {
// 检测图片存在
if(!file_exists($image)) {
return 0;
}
// 读取原图
$sourceInfo = getimagesize($image);
$sourceW = $sourceInfo[0]; // 取得图片的宽
$sourceH = $sourceInfo[1]; // 取得图片的高
// 相同宽和高,退出
if($sourceW == $sourceH) {
return 2;
}
// 设置原图和新图
$sourceMin = min($sourceW,$sourceH);
$sourceIm = imagecreatefromjpeg($image);
$newIm = imagecreatetruecolor($sourceMin, $sourceMin);
// 设定图像的混色模式
imagealphablending($newIm, false);
// 拷贝原图到新图
$posX = $posY = 0;
if($sourceW > $sourceH) {
$posX = floor(($sourceH-$sourceW)/2);
} else {
$posY = floor(($sourceW-$sourceH)/2);
}
imagecopy($newIm, $sourceIm, $posX, $posY, 0, 0, $sourceW, $sourceH);
// 生成图片替换原图
@unlink($image);
imagejpeg($newIm, $image);
return 1;
}