使用php调整上传的图片大小

时间:2016-12-18 10:38:18

标签: php

我正在尝试创建一个平台,用户可以在我的网站上传图像。首先调整图像大小,然后再将其移动到服务器上的特定文件夹。问题是,除了一件事以外,一切都在发挥作用。当调整大小过程完成时,它会切出图像的一部分,而不是实际调整图像大小。我试图找出问题所在,但我只是php的新手。你们对这个问题有什么建议吗?

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["image"]["name"]);
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    $file = $_FILES["image"]["tmp_name"];   

function resize_image($file, $width, $height) {
    list($w, $h) = getimagesize($file);
    /* calculate new image size with ratio */
    $ratio = max($width/$w, $height/$h);
    $h = ceil($height / $ratio);
    $x = ($w - $width / $ratio) / 2;
    $w = ceil($width / $ratio);
    /* read binary data from image file */
    $imgString = file_get_contents($file);
    /* create image from string */
    $image = imagecreatefromstring($imgString);
    $tmp = imagecreatetruecolor($width, $height);
    imagecopyresampled($tmp, $image,
    0, 0,
    $x, 0,
    $width, $height,
    $w, $h);
    imagejpeg($tmp, $file, 100);
    return $file;
    /* cleanup memory */
    imagedestroy($image);
    imagedestroy($tmp);
}

$check = getimagesize($_FILES["image"]["tmp_name"]);      
    if($check == false) {
    echo "Filen &auml;r ingen bild!&nbsp;<a href=addPost>Tillbaka</a>";
    exit;
    }
    if ($_FILES["image"]["size"] > 500000) {
    echo "Din bild &auml;r f&ouml;r stor!&nbsp;<a href=addPost>Tillbaka</a>";
    exit;
    }
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
    echo "Endast jpg, png, jpeg samt gif bilder &auml;r till&aring;tna!&nbsp;<a href=addPost>Tillbaka</a>";
    exit;
    }
    else {
    $temp = explode(".", $_FILES["image"]["name"]);
    $newfilename = round(microtime(true)) . '.' . end($temp);
    move_uploaded_file(resize_image($_FILES["image"]["tmp_name"], 200, 200), "uploads/" . $newfilename);
    chmod(UPLOAD_DIR . $newfilename, 0644);
    }

0 个答案:

没有答案