
02-Apr-2009, 18:43
|
 |
Junior Member
|
|
Join Date: Mar 2009
Location: Cyberspace, Earth
Posts: 53
|
|
|
Resize images without stretching or squeezing
PHP Code:
<?php
/*
* This script demonstrates the mathematics of resizing an image to a different
* width and height without stretching or squeezing the original image. If the
* source image has a different aspect ratio than the destination image, the
* source image will be cropped.
*
* Consider a source image with a width of 320 pixels and a height of 240
* pixels. The destination image is to be 80 pixels by 80 pixels. If these
* dimensions were passed directly to imagecopyresampled(), the resized image
* would appear to have a squeezed width. To prevent this, the width of the
* source image should be cropped to 240 pixels so that the ratio of its width
* to its height is 1:1, which is the same as the destination image's ratio.
* When the source image is resized, it will not appear squeezed.
*/
$src = imagecreatefromjpeg('sample.jpg'); // Source image
$dw = 80; // Destination image Width
$dh = 80; // Destination image Height
$sw = imagesx($src); // Source image Width
$sh = imagesy($src); // Source image Height
$wr = $sw / $dw; // Width Ratio (source:destination)
$hr = $sh / $dh; // Height Ratio (source:destination)
$cx = 0; // Crop X (source offset left)
$cy = 0; // Crop Y (source offset top)
if ($hr < $wr) // Height is the limiting dimension; adjust Width
{
$ow = $sw; // Old Source Width (temp)
$sw = $dw * $hr; // New virtual Source Width
$cx = ($ow - $sw) / 2; // Crops source width; focus remains centered
}
if ($wr < $hr) // Width is the limiting dimension; adjust Height
{
$oh = $sh; // Old Source Height (temp)
$sh = $dh * $wr; // New virtual Source Height
$cy = ($oh - $sh) / 2; // Crops source height; focus remains centered
}
// If the width ratio equals the height ratio, the dimensions stay the same.
$dst = imagecreatetruecolor($dw, $dh); // Destination image
imagecopyresampled($dst, $src, 0, 0, $cx, $cy, $dw, $dh, $sw, $sh);
// Previews the resized image (not saved)
header('Content-type: image/jpeg');
imagejpeg($dst);
?>

|
|