通过上传PHP

时间:2017-08-31 20:26:39

标签: javascript php gd

我一直在敲我的头几个小时,我不能为我的生活找出如何用简单的形式上传相同比例的图像。如果有人上传的图像大于水平或垂直2048像素,我想将其大小调整为2048像素,然后将其保存在文件夹中。

因为我基本上只用我的表格回到了划痕,所以我很遗憾没有给你看任何东西,但大部分时间都在搜索和阅读关于GD但是对我不起作用......

非常感谢任何提示!

编辑:

if(isset($con, $_POST['save_button'])){
    // IMAGE PROCESSING
    $name = $_FILES['file_upload']['name'];
    $tmp_name = $_FILES['file_upload']['tmp_name'];
    $type = $_FILES['file_upload']['type'];
    $size = $_FILES['file_upload']['size'];
    $error = $_FILES['file_upload']['error'];

    move_uploaded_file($tmp_name, "social_images/$name.jpg");

    function resize_image($img, $w, $h, $crop=FALSE) {
        list($width, $height) = getimagesize($img);
        $r = $width / $height;
        if ($crop) {
            if ($width > $height) {
                $width = ceil($width-($width*abs($r-$w/$h)));
            } else {
                $height = ceil($height-($height*abs($r-$w/$h)));
            }
            $newwidth = $w;
            $newheight = $h;
        } else {
            if ($w/$h > $r) {
                $newwidth = $h*$r;
                $newheight = $h;
            } else {
                $newheight = $w/$r;
                $newwidth = $w;
            }
        }
        $src = imagecreatefromjpeg($img);
        $dst = imagecreatetruecolor($newwidth, $newheight);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        return $dst;
    }

    $img = resize_image("social_images/$name.jpg", 780, 780);

    header("location: index.php");
    exit();
}

1 个答案:

答案 0 :(得分:2)

重新审核并重新测试:

<?php
function shazam($file, $w, $h) {
    list($width, $height) = getimagesize($file);

    if ($width > $height) {
        $r = ($w / $width);
        $newwidth = $w;
        $newheight = ceil($height * $r);
    } 

    if ($width < $height) {
        $r = ($h / $height);
        $newheight = $h;
        $newwidth = ceil($width * $r);
    } 

    if ($width == $height) {
        $newheight = $h;
        $newwidth = $w;
    }

    $src = imagecreatefromjpeg($file);
    $tgt = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($tgt, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    return $tgt;
}

$img = shazam("thepicwithpath.jpg", 850, 850);
imagejpeg($img, "theresizedpicwithpath.jpg", 75);
?>

请注意,最后的imagejpeg()实际上是生成新文件的内容。