php resize image on upload

后端 未结 12 1454
别跟我提以往
别跟我提以往 2020-11-27 04:09

I got a form where the user is inserting some data and also uploading an image.

To deal with the image, I got the following code:

define(\"MAX_SIZE\"         


        
12条回答
  •  抹茶落季
    2020-11-27 04:25

    Building onto answer from @zeusstl, for multiple images uploaded:

    function img_resize()
    {
    
      $input = 'input-upload-img1'; // Name of input
    
      $maxDim = 400;
      foreach ($_FILES[$input]['tmp_name'] as $file_name){
        list($width, $height, $type, $attr) = getimagesize( $file_name );
        if ( $width > $maxDim || $height > $maxDim ) {
            $target_filename = $file_name;
            $ratio = $width/$height;
            if( $ratio > 1) {
                $new_width = $maxDim;
                $new_height = $maxDim/$ratio;
            } else {
                $new_width = $maxDim*$ratio;
                $new_height = $maxDim;
            }
            $src = imagecreatefromstring( file_get_contents( $file_name ) );
            $dst = imagecreatetruecolor( $new_width, $new_height );
            imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
            imagedestroy( $src );
            imagepng( $dst, $target_filename ); // adjust format as needed
            imagedestroy( $dst );
        }
      }
    }
    

提交回复
热议问题