PHP图片调整大小

3

我有一个脚本,可以将文件上传到服务器,并将文件名添加到数据库中。但是在上传之前,我想限制图片的最大尺寸。例如,如果我上传一张1000 x 500像素的图片,它将被限制为200 x 100像素,并保留其原始比例。但是,如果我上传一张300 x 300像素的图片,它将被限制为200 x 200像素。

    <?php 

     //This is the directory where images will be saved 
     $target = "uploads/"; 
     $target = $target . basename( $_FILES['photo']['name']); 

     //This gets all the other information from the form 
     $name=$_POST['name']; 
     $pic=($_FILES['photo']['name']); 

     // Connects to your Database 
     mysql_connect("hostname", "username", "password") or die(mysql_error()) ; 
     mysql_select_db("database") or die(mysql_error()) ; 

     //Writes the information to the database 
     mysql_query("INSERT INTO `table` (name, photo) VALUES ('$name','$pic')") ; 

     //Writes the photo to the server 
     if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) 
     { 

     //Tells you if its all ok 
     echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; 
     } 
     else { 

     //Gives and error if its not 
     echo "Sorry, there was a problem uploading your file."; 
     } 
     ?> 

感谢您的帮助。

就目前而言,这是一个“帮我写代码”的请求,而不是一个问题。 - Pekka
你目前尝试了什么?你卡在哪个部分了吗?此外,请不要直接在 SQL 查询中使用 $_POST 数据,这是一个巨大的安全漏洞...请参考这个问题的解释 - Lepidosteus
1
在上传之前,使文件变小与PHP、MySQL或类似的东西无关。 - rabudde
抱歉,我没有意识到应该使用 $_GET 而不是 $_POST?我很新于 PHP,所以对所有事情都不太确定。我已经在谷歌上搜索了调整上传前图像大小的代码,但我无法弄清如何将其与我已有的代码集成。 - Lucy
@Lucy 这是一个安全漏洞,因为用户在表单中输入的任何内容都将上传到数据库中;请阅读这篇文章(或者谷歌搜索“SQL注入”);实质上,在将它们上传到数据库之前,您应该转义所有字符;最简单的方法是使用PHP的mysql_real_escape_string()函数。 - ChrisW
2个回答

4
据我所知,在上传图片之前无法调整其大小(我可能是错的!)。但是,当您上传图像时,它会进入临时文件。您可以调整临时图像的大小,并将调整后的图像复制到其最终目标位置。
由于(似乎)您想保持宽度恒定,因此不需要进行很多比例测试。
更新:
您应该能够简单地使用此代码替换原始代码。大部分内容都没有改变。
<?php

// resizes an image to fit a given width in pixels.
// works with BMP, PNG, JPEG, and GIF
// $file is overwritten
function fit_image_file_to_width($file, $w, $mime = 'image/jpeg') {
    list($width, $height) = getimagesize($file);
    $newwidth = $w;
    $newheight = $w * $height / $width;
    
    switch ($mime) {
        case 'image/jpeg':
            $src = imagecreatefromjpeg($file);
            break;
        case 'image/png';
            $src = imagecreatefrompng($file);
            break;
        case 'image/bmp';
            $src = imagecreatefromwbmp($file);
            break;
        case 'image/gif';
            $src = imagecreatefromgif($file);
            break;
    }
    
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    
    switch ($mime) {
        case 'image/jpeg':
            imagejpeg($dst, $file);
            break;
        case 'image/png';
            imagealphablending($dst, false);
            imagesavealpha($dst, true);
            imagepng($dst, $file);
            break;
        case 'image/bmp';
            imagewbmp($dst, $file);
            break;
        case 'image/gif';
            imagegif($dst, $file);
            break;
    }
    
    imagedestroy($dst);
}

// init file vars
$pic  = $_FILES['photo']['name'];
$target = 'uploads/' . basename( $_FILES['photo']['name']);
$temp_name = $_FILES['photo']['tmp_name'];
$type = $_FILES["photo"]["type"];

// Connects to your Database 
mysql_connect("hostname", "username", "password") or die(mysql_error()) ; 
mysql_select_db("database") or die(mysql_error()) ; 

// get form data
$name = mysql_real_escape_string(isset($_POST['name']) ? $_POST['name'] : 'No name');

//Writes the information to the database 
mysql_query("INSERT INTO `table` (name, photo) VALUES ('$name','$pic')") ; 

// resize the image in the tmp directorys
fit_image_file_to_width($temp_name, 200, $type);

//Writes the photo to the server
if(move_uploaded_file($temp_name, $target)) {

    //Tells you if its all ok 
    echo "The file ". basename( $_FILES['photo']['name'] ). " has been uploaded"; 

} else {

    //Gives and error if its not 
    echo "Sorry, there was a problem uploading your file."; 

}

?>

谢谢,我确实尝试了一下,看起来和我需要的很像,但是当我测试时什么也没有发生。不过可能是我没有正确地将代码添加到我的程序中。我应该使用您提供的代码而不是我原来使用的代码吗?还是应该将您的代码添加到我的代码中?抱歉问这种愚蠢的问题,我对PHP非常陌生。 - Lucy
谢谢你帮我解决这个问题。我尝试了你的新代码,但是什么也没有发生。我没有收到任何错误提示——只有一个空白页面和数据库中没有任何内容 :( - Lucy
我忽略了一个打字错误。我正在调试它,所以请耐心等待。:-) - Herbert
@Lucy:好的,我测试了所有内容,除了与数据库相关的代码,没有出现任何问题。我使用了2个JPEG文件和一个PNG文件进行测试,包括纵向(高而窄)、横向(短而宽)和正方形图像。它也支持BMP和GIF格式。不要忘记更改您的数据库变量(主机名、用户名等)。 - Herbert
1
@Lucy:非常感谢。是的,你可以直接更改宽度。更好的方法是,在脚本顶部将宽度分配给一个常量/变量。顺便说一句:在Stack Overflow上,习惯上通过点击答案旁边的大勾号来接受帮助你的答案。 :-) - Herbert
显示剩余2条评论

1

我以前使用过这个函数来生成缩略图,使其适合给定的尺寸并保持纵横比,也许你可以在某种程度上使用它:

function resize_img_nofill($src_name,$dst_name,$width,$height,$dontExpand=false) {
        $MAGIC_QUOTES = set_magic_quotes_runtime();
        set_magic_quotes_runtime(0);

        $type =  strtolower(substr(strrchr($src_name,"."),1));

        if($type == "jpg") {
            $src = imagecreatefromjpeg($src_name);
        } else if($type == "png") {
            $src = imagecreatefrompng($src_name);    
        } else if($type == "gif") {
            $src = imagecreatefromgif($src_name);    
        } else {
                if($src_name != $dst_name) copy($src_name,$dst_name);
                set_magic_quotes_runtime($MAGIC_QUOTES);
                return;
        }



        $d_width = $s_width = imagesx($src);
        $d_height = $s_height = imagesy($src);

        if($s_width*$height > $width*$s_height && (!$dontExpand || $width < $s_width)) {
            $d_width = $width;
            $d_height = (int)round($s_height*$d_width/$s_width);
        } else if(!$dontExpand || $height < $s_height) {
            $d_height = $height;
            $d_width = (int)round($s_width*$d_height/$s_height);
        }

        if($s_width != $d_width || $s_height != $d_height) {

                if($type == "jpg") {
                        $dst = imagecreatetruecolor($d_width,$d_height);
                } else if($type == "png") {
                $dst = imagecreate($d_width,$d_height);
                } else if($type == "gif") {
                $dst = imagecreate($d_width,$d_height);
                } 

                $white = imagecolorallocate($dst,255,255,255);
                imagefilledrectangle($dst,0,0,$d_width,$d_height,$white);
                imagecopyresampled($dst,$src,0,0,0,0,$d_width,$d_height,$s_width,$s_height);

                if($type == "jpg") 
                imagejpeg($dst,$dst_name, 80);  
                else if($type == "png")
                imagepng($dst,$dst_name);       
                else if($type == "gif")
                imagegif($dst,$dst_name);       

                imagedestroy($dst);
                imagedestroy($src);
        } else {
                copy($src_name,$dst_name);
        }


        set_magic_quotes_runtime($MAGIC_QUOTES);
        return array($d_width,$d_height);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接