Redimensionar Imagens com PHP
<?php
function open_image ($file) {
$im = @imagecreatefromjpeg($file);
if ($im !== false) { return $im; }
$im = @imagecreatefromgif($file);
if ($im !== false) { return $im; }
$im = @imagecreatefrompng($file);
if ($im !== false) { return $im; }
$im = @imagecreatefromgd($file);
if ($im !== false) { return $im; }
$im = @imagecreatefromgd2($file);
if ($im !== false) { return $im; }
$im = @imagecreatefromwbmp($file);
if ($im !== false) { return $im; }
$im = @imagecreatefromxbm($file);
if ($im !== false) { return $im; }
$im = @imagecreatefromxpm($file);
if ($im !== false) { return $im; }
$im = @imagecreatefromstring(file_get_contents($file));
if ($im !== false) { return $im; }
return false;
}
function resizeImage($im, $la=‘50%’, $al = ‘0′)
{
//Seta todas as strings como ’string’
settype($la, “string”);
settype($al, “string”);
// Carrega Imagem
$image = open_image($im);
if ($image == false) {
die (‘<strong>Erro ao abrir imagem</strong>’);
}
// Pega os tamanhos originais
$width = imagesx($image);
$height = imagesy($image);
// Checa o redimensionamendo, se é feito por % ou px
if (ereg(“[0-9]{1,3}%”,$la,$lixo)) {
$size = str_replace(“%”,“”,$la);
settype($size, “integer”);
$percent = floatval($la);
$percent /= 100;
$new_width = $width * $percent;
$new_height = $height * $percent;
}
elseif (isset($la) && $al == ‘0′ && !$al && $al == 0) {
settype($la, “integer”);
$new_width = floatval($la);
$new_height = $height * ($new_width/$width);
// Se apenas altura foi definida
}
elseif (isset($al) && $la == ‘0′ && !$la && $la == 0) {
settype($al, “integer”);
$new_height = floatval($al);
$new_width = $width * ($new_height/$height);
// Nova Largura e nova altura;
}
elseif (isset($la) && isset($al)) {
$new_height = floatval($la);
$new_width = floatval($la);
} else {
die (‘<strong>Nenhum tamanho foi especificado!’);
}
$image_resized = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Display resized image
header(‘Content-type: image/jpeg’);
imagejpeg($image_resized);
imagedestroy($image_resize);
}
resizeImage($_GET[‘img’],$_GET[‘width’],$_GET[‘height’]);
?>
Salve como resize.php
Usando:
<img src=”resize.php?img=imagem.jpg&width=50&height=50″/>
Você pode definir apenas width (com valor em px ou percentagem), apenas height ou os dois que o calculo será feito auto maticamente. Qualquer dúvida, poste um comentário!
November 21st, 2007 at 12:13
Opa Blz? adorei o script mais to com um probleminha!
eu queria que tipo
eu tenho uma imagem 1000×500
eu bote o tamanho dela como 200×200
ele redimencione por 5 pra não ficar esticado
sabe como?
agradeço desde ja abraço