图片压缩 裁剪处理

本文探讨了图片处理中的关键环节——图片压缩和裁剪。详细解释了各种压缩算法的工作原理,包括有损和无损压缩,并对比了它们的优缺点。同时,介绍了图片裁剪的常见方法和技术,如基于比例、固定尺寸和自由裁剪等,及其在不同场景的应用。此外,还提到了一些常用的图片处理库和工具,如 Pillow、OpenCV 和 ImageMagick,以及如何使用它们进行图片压缩和裁剪操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php
namespace Api\Controller;

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods' 'GET, POST'");

use Think\Controller;

class ImgShearController extends Controller
{

    public $uploadRoute;
    public $uploadDocx;



    public function __construct()
    {
        parent::__construct();
        $this->uploadRoute = "/Public/Uploads/ImgShear/" . date("Y") . '/' . date("m") . '/' . date("d") . '/';
    }
	

    //图片压缩
    public function imagecropper()
    {
        $source_path = $_REQUEST['url'];
        $target_width = $_REQUEST['width'];
        $target_height = $_REQUEST['height'];
		if(!$source_path || !$target_width || !$target_height){
		    echo json_encode(['code' => 1, 'msg' => '缺少参数']); exit;
		}else{
		    $source_info = getimagesize($source_path);
			$source_width = $source_info[0];
			$source_height = $source_info[1];
			$source_mime = $source_info['mime'];
			$source_ratio = $source_height / $source_width;
			$target_ratio = $target_height / $target_width;
			// 源图过高
			if ($source_ratio > $target_ratio)
			{
				$cropped_width = $source_width;
				$cropped_height = $source_width * $target_ratio;
				$source_x = 0;
				$source_y = ($source_height - $cropped_height) / 2;
			}
			// 源图过宽
			elseif ($source_ratio < $target_ratio)
			{
				$cropped_width = $source_height / $target_ratio;
				$cropped_height = $source_height;
				$source_x = ($source_width - $cropped_width) / 2;
				$source_y = 0;
			}
			// 源图适中
			else
			{
				$cropped_width = $source_width;
				$cropped_height = $source_height;
				$source_x = 0;
				$source_y = 0;
			}
			switch ($source_mime)
			{
				case 'image/gif':
					$source_image = imagecreatefromgif($source_path);
					break;
				case 'image/jpeg':
					$source_image = imagecreatefromjpeg($source_path);
					break;
				case 'image/png':
					$source_image = imagecreatefrompng($source_path);
					break;
				default:
					return false;
					break;
			}
			$target_image = imagecreatetruecolor($target_width, $target_height);
			$cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);
			// 裁剪
			imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
			// 缩放
			imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);
			$dest_dir = $_SERVER['DOCUMENT_ROOT'] . "/Public/Uploads/ImgShear/" . date("Y") . '/' . date("m") . '/' . date("d");
			if (!is_dir($dest_dir) || !is_writeable($dest_dir)) {
		
				$dest_dir1 = $_SERVER['DOCUMENT_ROOT'] . '/Public/Uploads/ImgShear/' . date("Y");
				$dest_dir2 = $_SERVER['DOCUMENT_ROOT'] . '/Public/Uploads/ImgShear/' . date("Y") . '/' . date("m");
				$dest_dir3 = $_SERVER['DOCUMENT_ROOT'] . '/Public/Uploads/ImgShear/' . date("Y") . '/' . date("m") . '/' . date("d");
				mkdir($dest_dir1, 0777, true);
				chmod($dest_dir1, 0777);
				mkdir($dest_dir2, 0777, true);
				chmod($dest_dir2, 0777);
				mkdir($dest_dir3, 0777, true);
				chmod($dest_dir3, 0777);
			}
		    $randNumber = mt_rand(00000, 99999). mt_rand(000, 999);
			$fileName =self::getRandomString(10).substr(md5($randNumber), 8, 16) .".jpg";
			imagepng($target_image, $dest_dir.'/'.$fileName);
			imagedestroy($target_image);
			$Oss_file ='.'.$this->uploadRoute.$fileName;
			$OssClient = new \Service\OssClient();
			$Oss_file_Name = $OssClient->uploadFile($Oss_file,'', $path = 'goods',$type=2);
			if($Oss_file_Name['code']==1000){
			 echo json_encode(['code' => 1, 'msg' => '上传成功', 'url' =>$Oss_file_Name['url']]);exit;
			}else{
			 echo json_encode(['code' => 1, 'msg' => '上传失败', 'url' =>'']);exit;
			}
			//保存图片到本地(两者选一)
			//$randNumber = mt_rand(00000, 99999). mt_rand(000, 999);
		    //$fileName = substr(md5($randNumber), 8, 16) .".jpg";
			//imagepng($target_image,'./'.$fileName);
			//imagedestroy($target_image);
			//直接在浏览器输出图片(两者选一)
			//   header('Content-Type: image/jpeg');
			//	imagepng($target_image);
			//	imagedestroy($target_image);
			//	imagejpeg($target_image);
			//	imagedestroy($source_image);
			//	imagedestroy($target_image);
			//	imagedestroy($cropped_image);
		}
    }
	
	
	
	//64上传
	public function uploadImg()
	{
		$base64_string = $_REQUEST['base64_string'];
		$target_width = $_REQUEST['width'];
        $target_height = $_REQUEST['height'];
		if(!$base64_string || !$target_width || !$target_height){
		    echo json_encode(['code' => 0, 'msg' => '缺少参数']); exit;
		}else{
		    //图片定一名称
			$savename = time().mt_rand(5, 10) . uniqid() . $this->getRandomString(8);//localResizeIMG压缩后的图片都是jpeg格式
			$source_savename = $savename.'.jpg';
			$source_sizename = $savename.$target_width."*".$target_height.'.jpg';
			//创建文件
			$dest_dir = $_SERVER['DOCUMENT_ROOT'] . "/Public/Uploads/ImgShear/" . date("Y") . '/' . date("m") . '/' . date("d");
			if (!is_dir($dest_dir) || !is_writeable($dest_dir)) {
				$dest_dir1 = $_SERVER['DOCUMENT_ROOT'] . '/Public/Uploads/ImgShear/' . date("Y");
				$dest_dir2 = $_SERVER['DOCUMENT_ROOT'] . '/Public/Uploads/ImgShear/' . date("Y") . '/' . date("m");
				$dest_dir3 = $_SERVER['DOCUMENT_ROOT'] . '/Public/Uploads/ImgShear/' . date("Y") . '/' . date("m") . '/' . date("d");
				mkdir($dest_dir1, 0777, true);
				chmod($dest_dir1, 0777);
				mkdir($dest_dir2, 0777, true);
				chmod($dest_dir2, 0777);
				mkdir($dest_dir3, 0777, true);
				chmod($dest_dir3, 0777);
			}
		    $savepath = $_SERVER['DOCUMENT_ROOT'] . "/Public/Uploads/ImgShear/" . date("Y") . '/' . date("m") . '/' . date("d").'/'.$source_savename;//上传的路径
		    $image = self::base64_to_img($base64_string, $savepath);
			$source_url = '/Public/Uploads/Phone/'.date("Y").'/'.date("m").'/'.date("d").'/' . $source_savename;
			
			$source_path = $savepath;
			$source_info = getimagesize($source_path);
			$source_width = $source_info[0];
			$source_height = $source_info[1];
			$source_mime = $source_info['mime'];
			$source_ratio = $source_height / $source_width;
			$target_ratio = $target_height / $target_width;
			// 源图过高
			if ($source_ratio > $target_ratio)
			{
				$cropped_width = $source_width;
				$cropped_height = $source_width * $target_ratio;
				$source_x = 0;
				$source_y = ($source_height - $cropped_height) / 2;
			}
			// 源图过宽
			elseif ($source_ratio < $target_ratio)
			{
				$cropped_width = $source_height / $target_ratio;
				$cropped_height = $source_height;
				$source_x = ($source_width - $cropped_width) / 2;
				$source_y = 0;
			}
			// 源图适中
			else
			{
				$cropped_width = $source_width;
				$cropped_height = $source_height;
				$source_x = 0;
				$source_y = 0;
			}
			switch ($source_mime)
			{
				case 'image/gif':
					$source_image = imagecreatefromgif($source_path);
					break;
				case 'image/jpeg':
					$source_image = imagecreatefromjpeg($source_path);
					break;
				case 'image/png':
					$source_image = imagecreatefrompng($source_path);
					break;
				default:
					return false;
					break;
			}
			$target_image = imagecreatetruecolor($target_width, $target_height);
			$cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);
			// 裁剪
			imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
			// 缩放
			imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);
		   // $randNumber = mt_rand(00000, 99999). mt_rand(000, 999);
			//$fileName =self::getRandomString(10).substr(md5($randNumber), 8, 16) .".jpg";
			imagepng($target_image, $dest_dir.'/'.$source_sizename);
			imagedestroy($target_image);

            $url = "www.baidu.com";
			$Oss_file1 ='.'.$this->uploadRoute.$source_sizename;
			$Oss_file2 ='.'.$this->uploadRoute.$source_savename;
			$OssClient = new \Service\OssClient();
			$Oss_file_Name1 = $OssClient->uploadFile($Oss_file1,'', $path = 'goods',$type=2);
			$Oss_file_Name2 = $OssClient->uploadFile($Oss_file2,'', $path = 'goods',$type=2);
			if($Oss_file_Name1['code']==1000  ||  $Oss_file_Name2['code']==1000 ){
				$data_info['code'] = 1;
				$data_info['msg'] = '上传成功';
				$data_info['url'] = $Oss_file_Name1['url'];
				$data_info['source'] = $Oss_file_Name2['url'];
				echo json_encode($data_info);exit;
			}else{
				$data_info['code'] = 2;
				$data_info['msg'] = '失败';
				$data_info['url'] = $url.$this->uploadRoute.$source_sizename;
				$data_info['source'] =$url.$this->uploadRoute.$source_savename;
				echo json_encode($data_info);exit;
			}	
		}	
	}





  	public function base64_to_img($base64_string, $output_file)
    {
        $ifp = fopen($output_file, "wb");
        fwrite($ifp, base64_decode($base64_string));
        fclose($ifp);
        return ($output_file);
    }

	
	
    //随机数
    public function getRandomString($len, $chars = null)
    {
        if (is_null($chars)) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        mt_srand(10000000 * (double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值