miercuri, 29 octombrie 2008

Image crop folosind PHP

Acum cateva zile mi-a trebuit sa redimensionez niste poze folosind PHP pentru a face pagina web sa se incarce mai repede. Am cautat putin pe net si am gasit urmatorul cod:

<?php

$nw = $_GET["width"];
$nh = $_GET["heigth"];
$source = $_GET["src"];

$size = getimagesize($source);

$w = $size[0];
$h = $size[1];

$simg = imagecreatefromjpeg($source);
$dimg = imagecreatetruecolor($nw, $nh);

$wm = $w/$nw;
$hm = $h/$nh;

$h_height = $nh/2;
$w_height = $nw/2;

if( $wm > $hm )
{
$adjusted_width = $w / $hm;
$half_width = $adjusted_width / 2;
$int_width = $half_width - $w_height;
imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
}
elseif( ($w < $h) || ($w == $h) )
{
$adjusted_height = $h / $wm;
$half_height = $adjusted_height / 2;
$int_height = $half_height - $h_height;
imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
}
else
{
imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
}

imagejpeg($dimg);

?>


Acest cod se salveaza intr-un fisier php (pentru exemplul meu am salvat codul in cropImage.php).

Pentru a utiliza acest cod procedati astfel: in fisierul unde vreti sa apara imaginea micsorata scrieti:

<img src="cropImage.php?src=cale/catre/poza&width=100&heigth=50" />

Sper sa va fie de folos si daca aveti imbunatatiri sau alte exemple nu ezitati sa lasati un comentariu.

Niciun comentariu: