PHP: create a cropped rectangle thumbnail

crop, image, php

Solution

Alright, this is probably a little bloated for your needs, but it gets the job done and it gets it done well..

First off, include or paste this class into your PHP code: http://pastebin.com/dnmiUVmk

Then, use the class similarly to the following:

<?php
// Replace 'picture' w/ whatever the name of the file upload.
// Alternately, specify an absolute path to an image already on the server.
$upload_image_tmp_filename = $_FILES['picture']['tmp_name'];
$saveas_image_filename = 'my_resized_image.png';
$max_width = 300;
$max_height = 40;

// If there was a problem, an exception is thrown.
try {
    // Load the image
    $picture = New Image($upload_image_tmp_filename);
    // Save the image, resized.
    $picture->saveFile($saveas_image_filename, $max_width, $max_height, True);
} catch(Exception $e) {
    print $e->getMessage();
}

Problem

I'm trying to resize and crop an image with `@imagecopyresampled` mantaining the original aspect ratio. The idea is: 1) I fix a dimension of the thumbnail (f.e. 300x40) 2) Crop starting to the center of the height I tried to read the documentation and a lot of other question on stackoverflow but without result. Anyone can help me?? My actual code is the following: ``` //$img_height, $img_width [original size of the image] $thumb_width = 300; $thumb_height = 40; $new_img = @imagecreatetruecolor($thumb_width, $thumb_height); $middle = floor($img_height/2); $src_x = 0; $src_y = $middle-($thumb_width/2); $src_w = $img_width; $aspectRatio = $img_width/$thumb_width; //$src_h = ????? $imgCopyRes = @imagecopyresampled( $new_img, $src_img, 0, 0, $src_x, $src_y, $thumb_width, $thumb_height, $src_w, $src_h); ``` EDIT : Thank you so much @Joshua Burns , reading your class and editing your code I have found the solution without including the entire file. Code: ``` $target_width = 300; $target_height = 40; $new_img = @imagecreatetruecolor($target_width, $target_height); $width_ratio = $target_width / $img_width; $height_ratio = $target_height / $img_height; if($width_ratio > $height_ratio) { $resized_width = $target_width; $resized_height = $img_height * $width_ratio; } else { $resized_height = $target_height; $resized_width = $img_width * $height_ratio; } // Drop decimal values $resized_width = round($resized_width); $resized_height = round($resized_height); // Calculations for centering the image $offset_width = round(($target_width - $resized_width) / 2); $offset_height = round(($target_height - $resized_height) / 2); $imgCopyRes = @imagecopyresampled( $new_img, $src_img, $offset_width, $offset_height, 0, 0, $resized_width, $resized_height, $img_width, $img_height); ```

Original source