How do I resize and convert an uploaded image to a PNG using GD?

前端 未结 9 1408
离开以前
离开以前 2020-12-05 16:08

I want to allow users to upload avatar-type images in a variety of formats (GIF, JPEG, and PNG at least), but to save them all as PNG database BLOBs

9条回答
  •  不知归路
    2020-12-05 16:59

    Something like this, perhaps:

    
     $max_width ) { 
          $percentage = ($height / ($width / $max_width)) > $max_height ?
               $height / $max_height :
               $width / $max_width;
       }
       elseif ( $height > $max_height) {
          $percentage = ($width / ($height / $max_height)) > $max_width ? 
               $width / $max_width :
               $height / $max_height;
       }
       $new_width = $width / $percentage;
       $new_height = $height / $percentage;
    
       //scaled image
       $out = imagecreatetruecolor($new_width, $new_height);
       imagecopyresampled($out, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    
       //output image
       imagepng($out);
    ?>
    

    I haven't tested the code so there might be some syntax errors, however it should give you a fair presentation on how it could be done. Also, I assumed a PNG file. You might want to have some kind of switch statement to determine the file type.

提交回复
热议问题