Use PHP to create thumbnails. (Cropped to square)

前端 未结 4 1654
借酒劲吻你
借酒劲吻你 2020-12-29 17:13

I have a php script im currently using that creates thumbnails based on a max width and height. However, I\'d like it to always create square images and crop the images whe

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 17:22

    You want to work out an offset rather than a new width/height so that the new sample stays in proportion, then use the offset when generating the new image and give it a fixed width/height so that it'll crop to a square. A quick example that would make a 100x100 thumb (note: untested),

    // Get dimensions of the src image.
    list($oldW, $oldH) = getimagesize($filename);
    
    // Work out what offset to use
    if ($oldH < $oldW) 
    {
        $offH = 0;
        $offW = ($oldW-$oldH)/2;
        $oldW = $oldH;
    } 
    elseif ($oldH > $oldW) 
    {
        $offW = 0;
        $offH = ($oldH-$oldW)/2;
        $oldH = $oldW;
    } 
    else 
    {
        $offW = 0;
        $offH = 0;
    }                
    
    // Resample the image into the new dimensions.
    $new = imagecreatetruecolor(100, 100);
    imagecopyresampled($new, $src, 0, 0, $offW, $offH, 100, 100, $oldW, $oldH);
    

提交回复
热议问题