本文实例讲述了PHP实现压缩图片尺寸并转为jpg格式的方法,分享给大家供大家参考,具体如下:
- function ImageToJPG($srcFile,$dstFile,$towidth,$toheight)
- {
- $quality=80;
- $data = @GetImageSize($srcFile);
- switch ($data['2'])
- {
- case 1:
- $im = imagecreatefromgif($srcFile);
- break;
- case 2:
- $im = imagecreatefromjpeg($srcFile);
- break;
- case 3:
- $im = imagecreatefrompng($srcFile);
- break;
- case 6:
- $im = ImageCreateFromBMP( $srcFile );
- break;
- }
- // $dstX=$srcW=@ImageSX($im);
- // $dstY=$srcH=@ImageSY($im);
- $srcW=@ImageSX($im);
- $srcH=@ImageSY($im);
- //$towidth,$toheight
- if($toheight/$srcW > $towidth/$srcH){
- $b = $toheight/$srcH;
- }else{
- $b = $towidth/$srcW;
- }
- //计算出图片缩放后的宽高
- // floor 舍去小数点部分,取整
- $new_w = floor($srcW*$b);
- $new_h = floor($srcH*$b);
- $dstX=$new_w;
- $dstY=$new_h;
- $ni=@imageCreateTrueColor($dstX,$dstY);
- @ImageCopyResampled($ni,$im,0,0,0,0,$dstX,$dstY,$srcW,$srcH);
- @ImageJpeg($ni,$dstFile,$quality);
- @imagedestroy($im);
- @imagedestroy($ni);
- }
- //ImageToJPG('源文件名','目标文件名',目标宽,目标高);
- ImageToJPG('test2.png','test2.jpg',80,50);
新闻热点
疑难解答