1. 程式人生 > >php圖片等比壓縮程式碼,支援jpg,png,gif,驗證gif動畫

php圖片等比壓縮程式碼,支援jpg,png,gif,驗證gif動畫

<?php
/**
 * Created by PhpStorm.
 * User: as
 * Date: 2016-12-01
 * Time: 8:38
 */
//圖片壓縮
function ImageCondens($filepase){
    list($new_width,$new_height,$imgtype)=getimagesize($filepase);
    if($new_width>550){//550為自定義寬度
        $scaling=$new_width/550;//縮放比例
        $picwidth=($new_width/$scaling);
        $picheight=($new_height/$scaling);
    }else{
        $picwidth=$new_width;
        $picheight=$new_height;
    }
    switch ($imgtype){
        case 1:
         $fp=fopen($filepase,'rb');
         $image_head = fread($fp,1024);
            fclose($fp);
         if(preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head)){//遮蔽gif動畫
             echo "<script>alert('系統不支援GIF動畫圖片');</script>";
         }else{
             if($image_head){
                 header('Content-Type:image/gif');
                 $img_wp=imagecreatetruecolor($picwidth,$picheight);
                 $img=imagecreatefromgif($filepase);
                 imagecopyresampled($img_wp,$img,0,0,0,0,$picwidth,$picheight,$new_width,$new_height);
                 imagejpeg($img_wp,null,100);
                 imagedestroy($img_wp);
             }
         }
         break;
        case 2:
            header('Content-Type:image/jpeg');
            $img_wp=imagecreatetruecolor($picwidth,$picheight);
            $img = imagecreatefromjpeg($filepase);
            imagecopyresampled($img_wp,$img,0,0,0,0,$picwidth,$picheight,$new_width,$new_height);
            imagejpeg($img_wp,null,100);
            imagedestroy($img_wp);
            break;
        case 3:
            header('Content-Type:image/png');
            $img_wp=imagecreatetruecolor($picwidth,$picheight);
            $img = imagecreatefrompng($filepase);
            imagecopyresampled($img_wp,$img,0,0,0,0,$picwidth,$picheight,$new_width,$new_height);
            imagejpeg($img_wp,null,100);
            imagedestroy($img_wp);
            break;
    }

}

ImageCondens("images/3.jpg");