imagecopyresampled in PHP, can someone explain it?

前端 未结 1 1306
孤街浪徒
孤街浪徒 2020-12-19 21:25

OK i thought i understood this function but i have a complete mental block on this one.

I wanted to create cropped thumbnails of size 75x75 from photos that are 800x

相关标签:
1条回答
  • 2020-12-19 22:18

    It's fairly simple, documented here

    The parameters:

    1) $dst_image, a valid GD handle representing the image you want to copy INTO
    2) $src_image, a valid GD Handle represending the image you're copying FROM

    3) $dst_x - X offset in the destination image you want to place the resampled image into
    4) $dst_y - Y offset, ditto

    5) $src_x - X offset in the source image you want to start copying from
    6) $src_y - Y offset, ditto

    7) $dst_x - X width of the newly resampled image in $dst_image
    8) $dst_y - Y width, ditto

    9) $src_x - X width of the area to copy out of the $src_image
    10) $src_y - Y width, ditto

    So...

    You've got a $src_image that's 800x536, and a $dst_image that's 75x75

           $width = 800                                $new_width = 75
    +-----------------------+                        +----+
    |                       |                        |    |
    |                       |                        |    | $new_height = 75
    |                       | $height = 536          +----+
    |                       |
    |                       |
    +-----------------------+
    

    Sounds like you want to take the middle chunk of the source image and make a thumbnail from that, right? This middle chunk should represent half the height & width of the original image, so you want:

    $start_X = floor($width / 4); //  200
    $width_Y = floor($height / 4); // 134
    
      200     400      200       
    +-----------------------+
    |     |          |      | 134
    |-----+----------+------|
    |     | This part|      | 268
    |-----+----------+------|
    |     |          |      | 134
    +-----------------------+
    
    $end_x = $start_X + (2 * $start_x) // 3 * $start_x = 600
    $end_y = $start_Y + (2 * $start_y) // 3 * $start_y = 402
    
    imagecopyresampled($src, $dst, 0, 0, $startX, $start_y, 75, 75, $end_x, $end_y);
                                   a  b  c        d         e   f   g       h
    

    a,b - start pasting the new image into the top-left of the destination image
    c,d - start sucking pixels out of the original image at 200,134
    e,f - make the resized image 75x75 (fill up the thumbnail)
    g,h - stop copying pixels at 600x402 in the original image

    Now, this is assuming that you want the thumbnail to be completely filled up. If you want the source image to be shrunk proportionally (so it has the same ration of height/width as the original, then you'll have to do some math to adjust the a,b and e,f parameters.

    0 讨论(0)
提交回复
热议问题