1. 程式人生 > >PHP一個方法調整影象大小(生成縮圖)

PHP一個方法調整影象大小(生成縮圖)

背景:

 天氣很冷

PHP程式碼:

/**
 * @param $imagedata    影象資料
 * @param $width        縮放寬度
 * @param $height       縮放高度
 * @param int $per      縮放比例,為0不縮放,>0忽略引數2、3的寬高
 * @return bool|string
 */
function image_resize($imagedata, $width, $height, $per = 0) {
    // 1 = GIF,2 = JPG,3 = PNG,4 = SWF,5 = PSD,6 = BMP,7 = TIFF(intel byte order),8 = TIFF(motorola byte order),9 = JPC,10 = JP2,11 = JPX,12 = JB2,13 = SWC,14 = IFF,15 = WBMP,16 = XBM

    // 獲取影象資訊
    list($bigWidth, $bigHight, $bigType) = getimagesizefromstring($imagedata);

    // 縮放比例
    if ($per > 0) {
        $width  = $bigWidth * $per;
        $height = $bigHight * $per;
    }

    // 建立縮圖畫板
    $block = imagecreatetruecolor($width, $height);

    // 啟用混色模式
    imagealphablending($block, false);

    // 儲存PNG alpha通道資訊
    imagesavealpha($block, true);

    // 建立原圖畫板
    $bigImg = imagecreatefromstring($imagedata);

    // 縮放
    imagecopyresampled($block, $bigImg, 0, 0, 0, 0, $width, $height, $bigWidth, $bigHight);

    // 生成臨時檔名
    $tmpFilename = tempnam(sys_get_temp_dir(), 'image_');

    // 儲存
    switch ($bigType) {
        case 1: imagegif($block, $tmpFilename);
            break;

        case 2: imagejpeg($block, $tmpFilename);
            break;

        case 3: imagepng($block, $tmpFilename);
            break;
    }

    // 銷燬
    imagedestroy($block);

    $image = file_get_contents($tmpFilename);

    unlink($tmpFilename);

    return $image;
}


使用方法:

header("content-type:image/png");

// 縮放影象
echo image_resize(file_get_contents('xxx.png'), 100, 100);