PHP 图像大小调整

发布于 2024-12-06 12:09:59 字数 1153 浏览 0 评论 0原文

我有一个脚本,可以将文件上传到服务器并将文件名添加到数据库中,但我想要在上传之前限制图像的最大尺寸。因此,如果我上传 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."; 
     } 
     ?> 

感谢您的帮助

I've got a script that uploads files to the server as well as adds the filename to a database, but what I'd like to do it restrict the maximum dimensions of the image before uploading. So if I upload an image that is 1000 x 500 it will be restricted but still keep it's dimensions and will be changed to 200 x 100, but an image that is 300 x 300 will be restricted to 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."; 
     } 
     ?> 

Thanks for your help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

女中豪杰 2024-12-13 12:09:59

据我所知,您无法在上传图像之前调整图像大小。 (我可能是错的!)但是,当您上传图像时,它会进入临时文件。您可以调整临时图像的大小并将调整大小的图像复制到其最终目的地。

由于(似乎)您希望保持宽度恒定,因此您实际上不需要进行大量比率测试。

更新:

您应该能够简单地使用它来代替原始代码。大部分都没有改变。

<?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."; 

}

?>

To my knowledge, you can’t resize the image before uploading it. (I could be wrong!) However, when you upload the image it goes into a temporary file. You can resize the temporary image and copy the resized image to its final destination.

Since (it seems) you want to keep the width constant, you don’t really need to do a lot of ratio tests.

Update:

You should be able to simply use this in place of your original code. Most of it is unchanged.

<?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."; 

}

?>
淤浪 2024-12-13 12:09:59

我过去使用这个函数来生成适合给定尺寸并保持纵横比的缩略图,也许您可​​以以某种方式使用它:

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);
}

I used in the past this function to generate thumbnails that fit in given dimensions keeping aspect ratio, maybe you can use it somehow:

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文