PHP Image Resizing

后端 未结 2 1611
没有蜡笔的小新
没有蜡笔的小新 2020-12-16 08:43

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 befo

2条回答
  •  天涯浪人
    2020-12-16 09:31

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

提交回复
热议问题