使用PHP动态调整图像大小

时间:2016-05-19 17:14:40

标签: php image

我正在构建一个壁纸网站,因此我需要能够在下载之前调整原始图像的大小。我尝试使用此代码来调整图像大小:

//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)

此代码适用于我,但我只想将输出发送到用户的浏览器,因为无法保存数千张额外的图像。有我可以使用的库,但我不想使用第三方代码段。有没有办法以我想要的方式改变这段代码? 感谢。

2 个答案:

答案 0 :(得分:0)

对于$ image函数,不要指定目标目录(null),否则将创建图像流。

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

那应该将图像发送给用户

答案 1 :(得分:0)

您只需设置正确的标头并回显输出即可。 Every PHP request "downloads a file" to the browser, more or less.您只需指定浏览器如何处理它。所以尝试类似的事情:

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

那应该为你做。