php GD add padding to image

前端 未结 1 1027
迷失自我
迷失自我 2021-02-08 00:57

I have found a few things on the web about PHP+GD regarding image manipulation, but none seem to give me what I am looking for.

I have someone upload an image of any dim

相关标签:
1条回答
  • 2021-02-08 01:19
    1. Open the original image
    2. Create a new blank image.
    3. Fill the new image with the background colour your want
    4. Use ImageCopyResampled to resize&copy the original image centered onto the new image
    5. Save the new image

    Instead of your switch statement you can also use

    $img = imagecreatefromstring( file_get_contents ("path/to/image") );
    

    This will auto detect the image type (if the imagetype is supported by your install)

    Updated with code sample

    $orig_filename = 'c:\temp\380x253.jpg';
    $new_filename = 'c:\temp\test.jpg';
    
    list($orig_w, $orig_h) = getimagesize($orig_filename);
    
    $orig_img = imagecreatefromstring(file_get_contents($orig_filename));
    
    $output_w = 200;
    $output_h = 200;
    
    // determine scale based on the longest edge
    if ($orig_h > $orig_w) {
        $scale = $output_h/$orig_h;
    } else {
        $scale = $output_w/$orig_w;
    }
    
        // calc new image dimensions
    $new_w =  $orig_w * $scale;
    $new_h =  $orig_h * $scale;
    
    echo "Scale: $scale<br />";
    echo "New W: $new_w<br />";
    echo "New H: $new_h<br />";
    
    // determine offset coords so that new image is centered
    $offest_x = ($output_w - $new_w) / 2;
    $offest_y = ($output_h - $new_h) / 2;
    
        // create new image and fill with background colour
    $new_img = imagecreatetruecolor($output_w, $output_h);
    $bgcolor = imagecolorallocate($new_img, 255, 0, 0); // red
    imagefill($new_img, 0, 0, $bgcolor); // fill background colour
    
        // copy and resize original image into center of new image
    imagecopyresampled($new_img, $orig_img, $offest_x, $offest_y, 0, 0, $new_w, $new_h, $orig_w, $orig_h);
    
        //save it
    imagejpeg($new_img, $new_filename, 80);
    
    0 讨论(0)
提交回复
热议问题