簡體   English   中英

使用PHP即時裁剪圖像大小

[英]Crop resize images on the fly using PHP

我正在建立一個牆紙網站,因此在下載之前,我需要能夠調整原始圖像的大小。 我嘗試使用以下代碼來調整圖像大小:

//resize and crop image by center
function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 80){
    $imgsize = getimagesize($source_file);
    $width = $imgsize[0];
    $height = $imgsize[1];
    $mime = $imgsize['mime'];

    switch($mime){
        case 'image/gif':
            $image_create = "imagecreatefromgif";
            $image = "imagegif";
            break;

        case 'image/png':
            $image_create = "imagecreatefrompng";
            $image = "imagepng";
            $quality = 7;
            break;

        case 'image/jpeg':
            $image_create = "imagecreatefromjpeg";
            $image = "imagejpeg";
            $quality = 80;
            break;

        default:
            return false;
            break;
    }

    $dst_img = imagecreatetruecolor($max_width, $max_height);
    $src_img = $image_create($source_file);

    $width_new = $height * $max_width / $max_height;
    $height_new = $width * $max_height / $max_width;
    //if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
    if($width_new > $width){
        //cut point by height
        $h_point = (($height - $height_new) / 2);
        //copy image
        imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
    }else{
        //cut point by width
        $w_point = (($width - $width_new) / 2);
        imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
    }

    $image($dst_img, $dst_dir, $quality);

    if($dst_img)imagedestroy($dst_img);
    if($src_img)imagedestroy($src_img);
}

這將調整大小:

resize_crop_image($width, $height, $image_URL, $save_URL)

這段代碼對我來說很好用,但是我只想將輸出發送到用戶的瀏覽器,因為不可能保存成千上萬的額外圖像。 我可以使用某些庫,但我不想使用第三方代碼段。 有沒有辦法以我想要的方式更改此代碼? 謝謝。

對於$ image函數,請不要指定目標目錄(空),否則將創建圖像流。

header("Content-type:{$mime}");

那應該將圖像發送給用戶

您只需要設置適當的標題並回顯輸出即可。 每個PHP請求或多或少都會“下載文件”到瀏覽器。 您只需要指定瀏覽器如何處理它即可。 因此,嘗試類似:

header("Content-Type: $mime");
header("Content-Disposition: attachment; filename=$dst_img");
echo $dst_img;

那應該為你做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM