Главная
>>
Каталог задач
>>
Веб-разработка
>>
Серверный скриптинг
>>
Работа с изображениями
>>
Масштабирование, пропорциональное изменение размеров картинки
Масштабирование, пропорциональное изменение размеров картинки
реализации: php, количество: 6
Aвтор: this
Дата: 26.03.2006
Просмотров: 86166
Рейтинг:
3/7,4.91(3818)
+
реализации(исходники)
+добавить
Задача возникает при создании превьюшек(небольших иконок) из имеющихся больших изображений. В данном случае необходимо сделать уменьшенный пропорциональный вариант нашей картинки, высота и ширина которого не будет превышать заданных значений.
Формализация
На входе:
- Путь к файлу содержащему исходное большое изображение
- Путь к файлу, в котором будет получена уменьшенная копия
- Максимально допустимая ширина уменьшенной копии
- Максимально допустимая высота уменьшенной копии
На выходе нужно чтобы по пути в п.2 - мы получили бы искомую превьюшку, размеры которой не превышают указанных.
Алгоритм
- Получаем размеры исходной картинки
- На их основе рассчитываем коэфициент пропорции по отношению к уменьшенной копии
- На основе рассчитанного коэфициэнта - получаем новые размеры.
- Уменьшаем исходное изображение до указанных размеров.
Все пункты кроме 2-го - не представляют большого интереса, т.к. реализуются специфическими фукнциями того или иного языка и легко находятся в документации.
П.2 - может быть реализован по-разному. Нужно найти такой коэфициэнт, который даст новые высоту и ширину, не превышающие указанные.
Для этого нужно рассчитывать пропорцию от большего значения из 2-х(высота и ширина исходной картинки):
// Рассчитываем коэфициент
// imgWidth, imgHeight - исходные размеры
if imgWidth > imgHeight
ratio = maxWidth / imgWidth
else
ratio = maxHeight / imgHeight
newWidth = ratio * imgWidth
newHeight = ratio * imgHeight
Реализации:
php(6)
+добавить реализацию
1)
Вычисление коэфициэнта пропорции от большей величины, code #99[автор:this]
function ResizeImg2($strSourceImagePath, $strDestImagePath, $intMaxWidth = 200, $intMaxHeight = 200)
{
$intImgWidth = $arrImageProps[0];
$intImgHeight = $arrImageProps[1];
$intImgType = $arrImageProps[2];
switch( $intImgType) {
case 1: $rscImg = ImageCreateFromGif($strSourceImagePath); break;
case 2: $rscImg = ImageCreateFromJpeg($strSourceImagePath); break;
case 3: $rscImg = ImageCreateFromPng($strSourceImagePath); break;
default: return false;
}
if ( !$rscImg) return false;
if ($intImgWidth > $intImgHeight) {
$fltRatio =
floatval($intMaxWidth /
$intImgWidth);
} else {
$fltRatio =
floatval($intMaxHeight /
$intImgHeight);
}
$intNewWidth =
intval($fltRatio *
$intImgWidth);
$intNewHeight =
intval($fltRatio *
$intImgHeight);
$rscNewImg = ImageCreate($intNewWidth, $intNewHeight);
if (!ImageCopyResized($rscNewImg, $rscImg, 0, 0,0, 0, $intNewWidth, $intNewHeight, $intImgWidth, $intImgHeight)) return false;
switch($intImgType) {
case 1: $retVal = ImageGIF($rscNewImg, $strDestImagePath); break;
case 3: $retVal = ImagePNG($rscNewImg, $strDestImagePath); break;
case 2: $retVal = ImageJPEG($rscNewImg, $strDestImagePath, 90); break;
default: return false;
}
ImageDestroy($rscNewImg);
return true;
}
// Тест:
$strTestImgPath =
dirname(__FILE__).
'/testimg.gif';
$strDestImgPath =
dirname(__FILE__).
'/testimg.preview.gif';
print (int
)ResizeImg2
($strTestImgPath,
$strDestImgPath,
300,
300);
2)
Вариант №1 из комментов к документации php, code #100[автор:-]
function resize($cur_dir, $cur_file, $newwidth, $output_dir) {
$dir_name = $cur_dir;
$filename = $cur_file;
$format='';
{
$format = 'image/jpeg';
}
{
$format = 'image/gif';
}
{
$format = 'image/png';
}
if($format!='')
{
$newheight=$height*$newwidth/$width;
switch($format)
{
case 'image/jpeg':
$source = imagecreatefromjpeg($filename);
break;
case 'image/gif';
$source = imagecreatefromgif($filename);
break;
case 'image/png':
$source = imagecreatefrompng($filename);
break;
}
$thumb = imagecreatetruecolor($newwidth,$newheight);
imagealphablending($thumb, false);
$source = @imagecreatefromjpeg("$filename");
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$filename="$output_dir/$filename";
@imagejpeg($thumb, $filename);
}
}
//call this function using
resize("./input folder", "picture_file_name", "width", "./output folder");
3)
Вариант №2 из комментов к документации php, code #101[автор:-]
/**
* Resize an image and keep the proportions
* @author Allison Beckwith <allison@planetargon.com>
* @param string $filename
* @param integer $max_width
* @param integer $max_height
* @return image
*/
function resizeImage($filename, $max_width, $max_height)
{
$width = $orig_width;
$height = $orig_height;
# taller
if ($height > $max_height) {
$width = ($max_height / $height) * $width;
$height = $max_height;
}
# wider
if ($width > $max_width) {
$height = ($max_width / $width) * $height;
$width = $max_width;
}
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0,
$width, $height, $orig_width, $orig_height);
return $image_p;
}
4)
Вариант №3 из комментов к документации php, code #102[автор:-]
header('Content-type: image/jpeg');
//$myimage = resizeImage('filename', 'newwidthmax', 'newheightmax');
$myimage = resizeImage('test.jpg', '150', '120');
function resizeImage($filename, $newwidth, $newheight){
if($width > $height && $newheight < $height){
$newheight = $height / ($width / $newwidth);
} else if ($width < $height && $newwidth < $width) {
$newwidth = $width / ($height / $newheight);
} else {
$newwidth = $width;
$newheight = $height;
}
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return imagejpeg($thumb);
}
5)
Вариант №4 из комментов к документации php, code #103[автор:-]
$picture = ""; # picture fileNAME here. not address
$max=150; # maximum size of 1 side of the picture.
/*
here you can insert any specific "if-else",
or "switch" type of detector of what type of picture this is.
in this example i'll use standard JPG
*/
$src_img=ImagecreateFromJpeg($picture);
$oh = imagesy($src_img); # original height
$ow = imagesx($src_img); # original width
$new_h = $oh;
$new_w = $ow;
if($oh > $max || $ow > $max){
$r = $oh/$ow;
$new_h = ($oh > $ow) ? $max : $max*$r;
$new_w = $new_h/$r;
}
// note TrueColor does 256 and not.. 8
$dst_img = ImageCreateTrueColor($new_w,$new_h);
ImageCopyResized($dst_img, $src_img, 0,0,0,0, $new_w, $new_h, ImageSX($src_img), ImageSY($src_img));
ImageJpeg($dst_img, "th_$picture");
6)
php image resize, code #628[аноним:Сергей]
function img_resize($src, $dest, $width, $height, $rgb = 0x000000, $quality = 100) {
return false;
}
if ($size === false) {
return false;
}
$icfunc = 'imagecreatefrom'.$format;
return false;
}
$x_ratio = $width / $size[0];
$y_ratio = $height / $size[1];
if ($height == 0) {
$y_ratio = $x_ratio;
$height = $y_ratio * $size[1];
} elseif ($width == 0) {
$x_ratio = $y_ratio;
$width = $x_ratio * $size[0];
}
$ratio =
min($x_ratio,
$y_ratio);
$use_x_ratio = ($x_ratio == $ratio);
$new_width =
$use_x_ratio ?
$width :
floor($size[0] *
$ratio);
$new_height = !
$use_x_ratio ?
$height :
floor($size[1] *
$ratio);
$new_left =
$use_x_ratio ?
0 :
floor(($width -
$new_width) /
2);
$new_top = !
$use_x_ratio ?
0 :
floor(($height -
$new_height) /
2);
$isrc = $icfunc($src);
$idest = imagecreatetruecolor($width, $height);
$rgb2 = imagecolorallocate($idest, 245, 245, 245);
imagefill($idest, 0, 0, $rgb2);
imagecopyresampled($idest, $isrc, $new_left, $new_top, 0, 0, $new_width, $new_height, $size[0], $size[1]);
imagejpeg($idest, $dest, $quality);
imagedestroy($isrc);
imagedestroy($idest);
return true;
}