1. 程式人生 > >php 壓縮圖片,保留圖片的畫素、透明度

php 壓縮圖片,保留圖片的畫素、透明度

    /**
     * @param  $picture 圖片資料流 比如file_get_contents(imageurl)返回的東東
     * @param $destfile 儲存路徑
     */    
    function miniImg($picture,$destfile)
    {
        //獲取源圖gd影象識別符號
        $srcImg = imagecreatefromstring($picture);
        $srcWidth = imagesx($srcImg);
        $srcHeight = imagesy($srcImg);
        //建立新圖
        $newWidth = round($srcWidth / 2);
        $newHeight = round($srcHeight / 2);
        $newImg = imagecreatetruecolor($newWidth, $newHeight);
        //分配顏色 + alpha,將顏色填充到新圖上
        $alpha = imagecolorallocatealpha($newImg, 0, 0, 0, 127);
        imagefill($newImg, 0, 0, $alpha);
        
        //將源圖拷貝到新圖上,並設定在儲存 PNG 影象時儲存完整的 alpha 通道資訊
        imagecopyresampled($newImg, $srcImg, 0, 0, 0, 0, $newWidth, $newHeight, $srcWidth, $srcHeight);
        imagesavealpha($newImg, true);
        imagepng($newImg,$destfile);
    }