2. make a thumbnail by above image, cut the middle square by request, for exmple 75 x 75
example http://www.drama.com.tw/question/cat.jpg
Code: Select all
<?php
/**
* $dir - source directory
* $file - file name
* $size - dimension
*/
function imgSquareThumbnail($dir, $file, $size) {
$ratioSize = 120; // resize image to 120 regardless the size
$realPosition = $dir . $file;
$thumbDir = $dir . 'thumbnails/'; // directory for thumbnail
if (file_exists($realPosition)) {
$fileName = current(explode('.', $file)); // filanem
$ext = strtolower(end(explode('.', $realPosition))); // extension name
$newName = $fileName . '_' . $size . 'x' . $size . '.' . 'jpg'; // new file name
// show image directly if file exist
if (file_exists($thumbDir . $newName)) {
echo '<img src="' . $thumbDir . $newName . '" />';
return;
}
switch ($ext) {
case 'jpg':
case 'jpeg':
$src = imagecreatefromjpeg($realPosition);
break;
case 'gif':
$src = imagecreatefromgif($realPosition);
break;
case 'png':
$src = imagecreatefrompng($realPosition);
break;
}
$srcW = imagesx($src); // source width
$srcH = imagesy($src); // source height
if ($srcW >= $srcH) {
// resize by height
$newW = intval($srcW / $srcH * $ratioSize); // new width
$newH = $ratioSize; // new hieght
} else {
// resize by width
$newW = $ratioSize; // new width
$newH = intval($srcH / $srcW * $ratioSize); // new height
}
// resize to 120
$im = imagecreatetruecolor($newW, $newH);
imagecopyresized($im, $src, 0, 0, 0, 0, $newW, $newH, $srcW, $srcH);
// resize to request
$im2 = imagecreatetruecolor($size, $size);
$coordX = ($newW - $size) / 2;
$coordY = ($newH - $size) / 2;
imagecopyresized($im2, $im, 0, 0, $coordX, $coordY, $size + $coordX, $size + $coordY, $newW, $newH);
imagejpeg($im2, $thumbDir . $newName, 100); // output
imagedestroy($im);
imagedestroy($im2);
echo '<img src="' . $thumbDir . $newName . '" />';
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>image customize</title>
<style type="text/css">
body {
font-size: 12px;
}
</style>
</head>
<body>
<?php
imgSquareThumbnail('img/', 'cat.gif', 75);
?><br />
</body>
</html>