您的位置:首页 > 文旅 > 美景 > 公司网页怎么修改_good设计网_免费开通网站_seo知识总结

公司网页怎么修改_good设计网_免费开通网站_seo知识总结

2025/4/18 9:51:25 来源:https://blog.csdn.net/luoluoyu2013/article/details/145783174  浏览:    关键词:公司网页怎么修改_good设计网_免费开通网站_seo知识总结
公司网页怎么修改_good设计网_免费开通网站_seo知识总结

 最近上传图片时发现用户经常上传一些后缀名为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]];
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com