views:

107

answers:

1

I'm using imagecopyresampled to create thumbnails based on a certain width and height. The problem I'm having is that their height is being squished. What I want is for all thumbnail images to be 140x84 and if their aspect ratio does not match that the top and bottom extra portions of the image are cropped to center.

Here is what I have so far, any ideas would be greatly appreciated.

// Create Thumbnail

        $imgsize = getimagesize($targetFile);
    switch(strtolower(substr($targetFile, -3))){
        case "jpg":
            $image = imagecreatefromjpeg($targetFile);    
        break;
        case "png":
            $image = imagecreatefrompng($targetFile);
        break;
        case "gif":
            $image = imagecreatefromgif($targetFile);
        break;
        default:
            exit;
        break;
    }

    $width = 140; //New width of image    
    $height = $imgsize[1]/$imgsize[0]*$width; //This maintains proportions

    $x_mid = $width/2;  //horizontal middle
    $y_mid = $height/2; //vertical middle

    $src_w = $imgsize[0];
    $src_h = $imgsize[1];


    $picture = imagecreatetruecolor($width, $height);
    imagealphablending($picture, false);
    imagesavealpha($picture, true);
    $bool = imagecopyresampled($picture, $image, 0, 0, 0, ($y_mid-(84/2)), $width, $height, $src_w, $src_h); 

    if($bool){
        switch(strtolower(substr($targetFile, -3))){
            case "jpg":
                header("Content-Type: image/jpeg");
                $bool2 = imagejpeg($picture,$file_dir."/thumbs/".$imageName,85);
            break;
            case "png":
                header("Content-Type: image/png");
                imagepng($picture,$file_dir."/thumbs/".$imageName);
            break;
            case "gif":
                header("Content-Type: image/gif");
                imagegif($picture,$file_dir."/thumbs/".$imageName);
            break;
        }
    }


    imagedestroy($picture);
    imagedestroy($image);
A: 

You need to first work out if you're going to re-size your image based on it's height or width. You'd usually work this out depending if your original image is portrait or landscape, and the orientation of your desired image size. You then need to work out the other edge programmatically from your choice.

Once you have, you can simple resample your original image at (0,0) and the over-hanging image data will be truncated.

Martin Bean