//$imgSrc为图片base64流
if (preg_match('/^(data:\s*image\/(\w+);base64,)/',$imgSrc,$result)){
$imgSrc = base64_decode(str_replace($result[1], '', $imgSrc));
}
else{
$imgSrc = base64_decode($imgSrc);
}
$this->imageHandle($imgSrc)
/**
* 上传图片处理(压缩,调整分辨率等等)
* @param $imgsrc
* @return string
* @throws ImagickException
*/
private function imageHandle($imgsrc){
//压缩图片
$image = new \Imagick();
$image->readImageBlob($imgsrc);
$compression_type = Imagick::COMPRESSION_JPEG;
$image->setImageCompression($compression_type);
$image->setImageCompressionQuality(50);
$srcImage = $image->getImageGeometry(); //获取源图片宽和高
//图片等比例缩放宽和高设置 ,根据宽度设置等比缩放
$thumb_width = 500;
$thumb_height = 500;
$scale_org = $srcImage['width'] / $srcImage['height'];
if ($srcImage['width'] / $thumb_width > $srcImage['height'] / $thumb_height) {
$newX = $thumb_width;
$newY = $thumb_width / $scale_org;
} else {//原始图片比较高,则以高度为准
$newX = $thumb_height * $scale_org;
$newY = $thumb_height;
}
$image->thumbnailImage($newX, $newY); //按照比例进行缩
//修复图片旋转bug
$orientation = $image->getImageOrientation();
switch($orientation) {
case imagick::ORIENTATION_BOTTOMRIGHT:
$image->rotateimage("#000", 180); // rotate 180 degrees
break;
case imagick::ORIENTATION_RIGHTTOP:
$image->rotateimage("#000", 90); // rotate 90 degrees CW
break;
case imagick::ORIENTATION_LEFTBOTTOM:
$image->rotateimage("#000", -90); // rotate 90 degrees CCW
break;
}
$imgsrc = $image->getImageBlob();
$image->clear(); // 这一步需要执行,不然可能造成内存泄漏
return base64_encode($imgsrc);
}