PHP调整图像大小,转换为jpg,并在浏览器中显示

时间:2013-04-10 03:27:01

标签: php forms upload image-resizing image-conversion

我有一个表单来上传文件:

<form method="POST" action="upload-image.php">
    <input type="file" name="file"><br>
    <input type="submit" value="Submit">
</form>

用于调整上传文件(图像)大小的PHP代码,将其转换为JPG,并在浏览器中显示。

<?php
function image_to_jpg($src_file){
    $file = $_FILES["file"]["name"];
    $ext = end(explode(".",$file));
    list($width_orig,$height_orig) = getimagesize($src_file);
    $width  = 128;
    $height = 128;
    ini_set("memory_limit","32M");
    if($ext == "jpg" || $ext == "jpeg"){
        $image = imagecreatefromjpeg($file);
    }
    if($ext == "gif"){
            $image = imagecreatefromgif($file); 
    }
    if($ext == "png"){
        $image = imagecreatefrompng($file);
    }
    $new_image = imagecreatetruecolor($width,$height);
    imagecopyresampled($new_image,$image,0,0,0,0,$width,$height,$width_orig,height_orig);
    $dest_file = "ok.jpg";
    header("Content-Type: image/jpeg");
    imagejpeg($new_image,$dest_file);
}
$src_file = $_FILES["file"]["tmp_name"];
image_to_jpg($src_file);
?>

它不起作用。它显示一个空白图像。我的错误是什么?

注意:代码改编自帖子:

How do I resize and convert an uploaded image to a PNG using GD

1 个答案:

答案 0 :(得分:0)

因为您使用imagejpeg($new_image,$dest_file);您的缩放图像被写入ok.jpg。不要使用第二个参数直接输出到浏览器。

header("Content-Type: image/jpeg");
imagejpeg($new_image);
imagedestroy($new_image);
exit;