最近上传图片时发现用户经常上传一些后缀名为jpg格式而实际图片格式为png的图片。导致生成合成图片时报错。因此写了重写图片为jpg图片的方法。如下所示:
/*** 重写图片成jpg图片* @param $sourceFile 原始图片文件* @param $targetDir 目标目录* @param $quality 图片质量* @return string* @throws Exception*/ function convertImageToJpg($sourceFile, $targetDir, $quality = 85) {ini_set('memory_limit', '256M');// 检查GD库是否可用if (!extension_loaded('gd') || !function_exists('gd_info')) {//throw new Exception('GD库未安装');return ['code'=>4001,'msg'=>'GD库未安装'];}// 验证源文件if (!file_exists($sourceFile)) {// throw new Exception('源文件不存在');return ['code'=>4002,'msg'=>'源文件不存在'];}// 获取图片信息$imageInfo = @getimagesize($sourceFile);if (!$imageInfo) {//throw new Exception('无效的图片文件');return ['code'=>4003,'msg'=>'无效的图片文件'];}if($imageInfo[0] > 4000 || $imageInfo[1] > 4000){return ['code'=>4000,'msg'=>'图片分辨率不可大于4000*4000像素'];}// 生成目标路径$filename = pathinfo($sourceFile, PATHINFO_FILENAME);$targetPath = rtrim($targetDir, '/') . '/' . $filename . '.jpg';// 根据MIME类型创建图像资源$mimeType = $imageInfo['mime'];switch ($mimeType) {case 'image/jpeg'://如果是jpg,不用重写,直接返回路径return ['code'=>200,'msg'=>'成功','data'=>['filePath'=>$targetPath]];$image = imagecreatefromjpeg($sourceFile);break;case 'image/png':$image = imagecreatefrompng($sourceFile);break;case 'image/gif':$image = imagecreatefromgif($sourceFile);break;case 'image/webp':$image = imagecreatefromwebp($sourceFile);break;case 'image/bmp':$image = imagecreatefrombmp($sourceFile);break;default:// throw new Exception('不支持的图片格式: ' . $mimeType);return ['code'=>4004,'msg'=>'不支持的图片格式'. $mimeType];}// 处理透明背景(PNG/GIF)if (in_array($mimeType, ['image/png', 'image/gif'])) {$width = imagesx($image);$height = imagesy($image);// 创建新画布并填充白色背景$jpg = imagecreatetruecolor($width, $height);$white = imagecolorallocate($jpg, 255, 255, 255);imagefill($jpg, 0, 0, $white);imagecopy($jpg, $image, 0, 0, 0, 0, $width, $height);imagedestroy($image);$image = $jpg;}// 保存JPG文件if (!imagejpeg($image, $targetPath, $quality)) {//throw new Exception('JPG文件保存失败');return ['code'=>4005,'msg'=>'JPG文件保存失败'];}// 释放内存imagedestroy($image);//return $targetPath;return ['code'=>200,'msg'=>'成功','data'=>['filePath'=>$targetPath]]; }