PHP图片压缩的方法
2016-02-04 17:03
621 查看
项目里要求上传图片并进行缩放、压缩质量保存到服务器。
起初用php的image函数,结果jpg格式的图片保存正常,png格式的图片保存到服务器后损坏,大小变为0,方法如下:
if ($imageType == '.jpg') {
$src = @imagecreatefromjpeg ($url_tmp);
list($width,$height) = getimagesize($url_tmp);
$newwidth = 500;
$newheight = ($height/$width)*500;
$tmp = imagecreatetruecolor($newwidth,$newheight);
imagecopyresized($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$output = imagejpeg($tmp, $url_tmp, 50);
imagedestroy($tmp);
} elseif ($imageType == '.jpg') {
$src = @imagecreatefrompng ($url_tmp);
list($width,$height) = getimagesize($url_tmp);
$newwidth = 500;
$newheight = ($height/$width)*500;
$tmp = imagecreatetruecolor($newwidth, $newheight);
imagecopyresized($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$output = imagepng($tmp, $url_tmp, 50);//此行输出也为1,但保存到服务器就损坏了;后来发现对png图片用imagejpeg也能保存成功为png图片且未损坏。
imagedestroy($tmp);
}
if (!$output) {
echo '图片压缩失败';
}
后来更改方法,引入了ThinkImage图片处理库,解决了jpg和png图片压缩、压质的问题,具体见下面链接:
http://www.thinkphp.cn/extend/291.html
起初用php的image函数,结果jpg格式的图片保存正常,png格式的图片保存到服务器后损坏,大小变为0,方法如下:
if ($imageType == '.jpg') {
$src = @imagecreatefromjpeg ($url_tmp);
list($width,$height) = getimagesize($url_tmp);
$newwidth = 500;
$newheight = ($height/$width)*500;
$tmp = imagecreatetruecolor($newwidth,$newheight);
imagecopyresized($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$output = imagejpeg($tmp, $url_tmp, 50);
imagedestroy($tmp);
} elseif ($imageType == '.jpg') {
$src = @imagecreatefrompng ($url_tmp);
list($width,$height) = getimagesize($url_tmp);
$newwidth = 500;
$newheight = ($height/$width)*500;
$tmp = imagecreatetruecolor($newwidth, $newheight);
imagecopyresized($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$output = imagepng($tmp, $url_tmp, 50);//此行输出也为1,但保存到服务器就损坏了;后来发现对png图片用imagejpeg也能保存成功为png图片且未损坏。
imagedestroy($tmp);
}
if (!$output) {
echo '图片压缩失败';
}
后来更改方法,引入了ThinkImage图片处理库,解决了jpg和png图片压缩、压质的问题,具体见下面链接:
http://www.thinkphp.cn/extend/291.html
相关文章推荐
- 一个关于if else容易迷惑的问题
- PHP5.2.*防止Hash冲突拒绝服务攻击的Patch
- 深入理解PHP之匿名函数
- JSP/PHP基于Ajax的分页功能实现
- 关于PHP通过PDO用中文条件查询MySQL的问题。
- 什么是设计模式
- PHP数据库长连接mysql_pconnect的细节
- Php Installing An Expansion
- PHP+Apache在Windows 9x下的安装和配置
- IIS 6 的 PHP 最佳配置方法
- 安装Apache和PHP的一些补充
- Linux Apache+MySQL+PHP
- 建立Apache+PHP+MySQL数据库驱动的动态网站
- PHP 5.3.0 安装分析心得
- apache 环境下 php 的配置注意事项
- ASP.NET、ASP、PHP、JSP之间有什么区别?
- PHP VBS JS 函数 对照表
- C语言实现的统计php代码行数功能源码(支持文件夹、多目录)
- php xml 入门学习资料