The Deployer

October 26, 2007

PHP JPEG image resizing

Filed under: PHP — Lucian Daniliuc @ 06:22

Destul de des, atunci cand dezvoltam orice fel de site in care clientul trebuie sa poata pune pe site niste imagini, mai mult ca sigur ca acele imagini sunt de cativa megapixeli si afisarea lor la dimensiunile dorite este de multe ori un task destul de dificil de realizat. Asa am gasit pe netlobo.com un articol dragut cu o functie simpla si scurta care face resize la orice jpeg in anumite dimensiuni maximale, fara sa distorsioneze imaginea:


function resampimagejpg( $forcedwidth, $forcedheight, $sourcefile, $destfile )
{

$fw = $forcedwidth;
$fh = $forcedheight;
$is = getimagesize( $sourcefile );
if(
$is[0] >= $is[1] )
{
$orientation = 0;
}
else
{
$orientation = 1;
$fw = $forcedheight;
$fh = $forcedwidth;
}
if (
$is[0] > $fw || $is[1] > $fh )
{
if( (
$is[0] - $fw ) >= ( $is[1] - $fh ) )
{
$iw = $fw;
$ih = ( $fw / $is[0] ) * $is[1];
}
else
{
$ih = $fh;
$iw = ( $ih / $is[1] ) * $is[0];
}
$t = 1;
}
else
{
$iw = $is[0];
$ih = $is[1];
$t = 2;
}
if (
$t == 1 )
{
$img_src = imagecreatefromjpeg( $sourcefile );
$img_dst = imagecreatetruecolor( $iw, $ih );
imagecopyresampled( $img_dst, $img_src, 0, 0, 0, 0, $iw, $ih, $is[0], $is[1] );
if( !
imagejpeg( $img_dst, $destfile, 90 ) )
{
exit( );
}
}
else if (
$t == 2 )
{
copy( $sourcefile, $destfile );
}
}

?>

Daca acest copy-paste nu arata chiar ok, vezi articolul original.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress