压缩和旋转上传的图片
2019-12-25 本文已影响0人
玛瑙鑫
public function save()
{
$file = $_FILES['file'];
dump_log('原始凭证:', $file);
//原图
$dst_image = imagecreatefromstring(file_get_contents($file['tmp_name']));
//获取图片宽高
list($file_width, $file_height) = getimagesize($file['tmp_name']);
dump_log('file_width:', $file_width);
dump_log('file_height:', $file_height);
//定义缩略图宽度
$width = Db::name('config')
->order('id desc')
->value('orig_paper_width');
$height = Db::name('config')
->order('id desc')
->value('orig_paper_height');
dump_log('系统设置宽度:', $width);
dump_log('系统设置高度:', $height);
if ($file_height <= $height && $file_width <= $width) {
//如果宽度和高度均未超出 则保存原图尺寸
$width = $file_width;
$height = $file_height;
} elseif ($file_width > $width && $file_height < $height) {
//如果宽度超了 高度未超 高度为原图 宽度自适应
$height = $file_height;
$width = $file_width / $file_height * $height;
} elseif ($file_height > $height && $file_width < $width) {
//如果高度超了 宽度未超 宽度原图 高度自适应
$width = $file_width;
$height = $file_height / $file_width * $width;
}
dump_log('生成图片宽度:', $width);
dump_log('生成图片高度:', $height);
//缩略图
$thumb_img = imagecreatetruecolor($width, $height);
//文件名和后缀以'/'分开 得到一个$suffix数组
$file_type = explode('/', $file['type']);
$img_types = ['jpeg', 'png', 'gif'];
//获取图片后缀
$img_type = (in_array($file_type[1], $img_types)) ? $file_type[1] : 'png';
//设置图片上传名称 uniqid基于当前时间微妙数计算的唯一的ID
$img_name = mt_rand(100000, 999999).'_'.time().'.'.$img_type;
//通过图片类型设置不同格式上传至文件
$fn_name = 'image'.$img_type;
//图片存储路径
$thumb_path = ROOT_PATH.'order_img/'; //缩略图存放路径
imagecopyresampled($thumb_img, $dst_image, 0, 0, 0, 0, $width, $height, $file_width, $file_height);
//上传缩略图片(图片w尺寸200,存储路径)
$result = $fn_name($thumb_img, $thumb_path.$img_name);
dump_log('图片上传结果:', $result);
dump_log('路径:', $thumb_path.$img_name);
if ($height > $width) {
$this->imgturn($thumb_path.$img_name);
}
if ($result) {
ajaxReturn(0, '获取成功', '/order_img/'.$img_name);
} else {
ajaxReturn(1, '上传失败', '上传失败');
}
}
function imgturn($src, $direction = 1)
{
$ext = pathinfo($src)['extension'];
dump_log('ext:', $ext);
switch ($ext) {
case 'gif':
$img = imagecreatefromgif($src);
break;
case 'jpg':
case 'jpeg':
$img = imagecreatefromjpeg($src);
break;
case 'png':
$img = imagecreatefrompng($src);
break;
default:
die('图片格式错误!');
break;
}
$width = imagesx($img);
$height = imagesy($img);
$img2 = imagecreatetruecolor($height, $width);
//顺时针旋转90度
if ($direction == 1) {
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
imagecopy($img2, $img, $height - 1 - $y, $x, $x, $y, 1, 1);
}
}
} else {
if ($direction == 2) {
//逆时针旋转90度
for ($x = 0; $x < $height; $x++) {
for ($y = 0; $y < $width; $y++) {
imagecopy($img2, $img, $x, $y, $width - 1 - $y, $x, 1, 1);
}
}
}
}
dump_log('走到这里啦');
switch ($ext) {
case 'jpg':
case "jpeg":
imagejpeg($img2, $src, 9);
break;
case "gif":
imagegif($img2, $src, 9);
break;
case "png":
imagepng($img2, $src, 9);
break;
default:
die('图片格式错误!');
break;
}
imagedestroy($img);
imagedestroy($img2);
dump_log('竟然完成了');
}