quinta-feira, 31 de maio de 2012

Função para Crop de imagens no PHP

O CÓDIGO:



function CroppedThumbnail($imgSrc,$thumbnail_width,$thumbnail_height) { //$imgSrc is a FILE - Returns an image resource.

if (!file_exists($imgSrc)) {
return "";
}

$imagem_file = ultimo_elemento($imgSrc, '/');
    $novo_path_imagem = str_replace($imagem_file, "thumb_".$imagem_file, $imgSrc);

if(file_exists($novo_path_imagem)){
return $novo_path_imagem;
}

    //getting the image dimensions
    list($width_orig, $height_orig) = getimagesize($imgSrc);
    $myImage = imagecreatefromjpeg($imgSrc);
    $ratio_orig = $width_orig/$height_orig;

    if ($thumbnail_width/$thumbnail_height > $ratio_orig) {
       $new_height = $thumbnail_width/$ratio_orig;
       $new_width = $thumbnail_width;
    } else {
       $new_width = $thumbnail_height*$ratio_orig;
       $new_height = $thumbnail_height;
    }

    $x_mid = $new_width/2;  //horizontal middle
    $y_mid = $new_height/2; //vertical middle

    $process = imagecreatetruecolor(round($new_width), round($new_height));

    imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
    $thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
    imagecopyresampled($thumb, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)), $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);

    imagedestroy($process);
    imagedestroy($myImage);
    imagejpeg($thumb, $novo_path_imagem);

    return $novo_path_imagem;
}


O USO:

<img src=" < ?=CroppedThumbnail($foto,161,220);?>" width="161" height="220" alt="foto">

Nenhum comentário:

Postar um comentário