2010-07-15 10 views
11

buscando crear miniaturas que tengan una dimensión de 100px por 100px. He visto muchos artículos que explican los métodos, pero la mayoría termina teniendo el ancho! = alto si se debe mantener la relación de dimensiones.Imagen de recorte de PHP para corregir el ancho y la altura sin perder la relación de dimensión

por ejemplo, tengo una imagen de 450px por 350px. Me gustaría recortar a 100px por 100px. si tuviera que mantener la relación, terminaría teniendo 100px por 77px. esto lo hace feo cuando estoy listando estas imágenes en una fila y columna. sin embargo, una relación de imagen sin dimensiones también se verá terrible.

he visto imágenes de flickr y se ven fantásticas. por ejemplo:
miniatura: http://farm1.static.flickr.com/23/32608803_29470dfeeb_s.jpg
tamaño medio: http://farm1.static.flickr.com/23/32608803_29470dfeeb.jpg
gran tamaño: http://farm1.static.flickr.com/23/32608803_29470dfeeb_b.jpg

tks

+0

ohh ahora sé por qué alguien me recriminó por ese b4. Debo hacer clic en el signo de marcar !! no lo he notado. de acuerdo, déjame ver las respuestas – nuttynibbles

Respuesta

34

Esto se realiza utilizando sólo una parte de la imagen como la imagen en miniatura que tiene un 1: aspecto 1 relación (principalmente el centro de la imagen). Si miras de cerca puedes verlo en la miniatura de flickr.

Porque tiene "cultivo" en su pregunta, no estoy seguro de si aún no sabía esto, pero ¿qué quiere saber entonces?

Para utilizar recorte, aquí es un ejemplo:

//Your Image 
$imgSrc = "image.jpg"; 

//getting the image dimensions 
list($width, $height) = getimagesize($imgSrc); 

//saving the image into memory (for manipulation with GD Library) 
$myImage = imagecreatefromjpeg($imgSrc); 

// calculating the part of the image to use for thumbnail 
if ($width > $height) { 
    $y = 0; 
    $x = ($width - $height)/2; 
    $smallestSide = $height; 
} else { 
    $x = 0; 
    $y = ($height - $width)/2; 
    $smallestSide = $width; 
} 

// copying the part into thumbnail 
$thumbSize = 100; 
$thumb = imagecreatetruecolor($thumbSize, $thumbSize); 
imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide); 

//final output 
header('Content-type: image/jpeg'); 
imagejpeg($thumb); 
+0

Hola skoschnike * comprueba si escribí tu nombre correctamente =) * que me ha pasado por la cabeza. pero no tengo idea de cómo hacer eso. cuidado de compartir? – nuttynibbles

+0

hey sven, probé tu script y funciona muy bien. tk tanto. impecable – nuttynibbles

+0

hey sven, solo tengo una pregunta. usar ur script funciona muy bien. pero me di cuenta de que la calidad de la imagen después del recorte no es la misma que en el original. por ejemplo, tomé una foto de muestra de flickr y recorto a la misma dimensión y se ven diferentes. alguna solución para conservar la calidad? – nuttynibbles

0

me gusta usar GDlib que jugar con las imágenes, es increíblemente fácil trabajar con él también. Hay muchas publicaciones y tutoriales en el blog. Sin embargo, recomendaría utilizar una clase para él o similar, ya que cuidar todas las variaciones de la imagen puede consumir mucho tiempo.

+0

¿Te apetece esto quizás? http://pear.php.net/package/Image_Transform –

3

Recortar imagen cuadrada con base en menor anchura o altura

public function croppThis($target_url) { 

    $this->jpegImgCrop($target_url); 

} 

$ target_url - es Nombre de la imagen.

public function jpegImgCrop($target_url) {//support 



    $image = imagecreatefromjpeg($target_url); 
    $filename = $target_url; 
    $width = imagesx($image); 
    $height = imagesy($image); 
    $image_type = imagetypes($image); //IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM 

    if($width==$height) { 

    $thumb_width = $width; 
    $thumb_height = $height; 

    } elseif($width<$height) { 

    $thumb_width = $width; 
    $thumb_height = $width; 

    } elseif($width>$height) { 

    $thumb_width = $height; 
    $thumb_height = $height; 

    } else { 
    $thumb_width = 150; 
    $thumb_height = 150; 
    } 

    $original_aspect = $width/$height; 
    $thumb_aspect = $thumb_width/$thumb_height; 

    if ($original_aspect >= $thumb_aspect) { 

    // If image is wider than thumbnail (in aspect ratio sense) 
    $new_height = $thumb_height; 
    $new_width = $width/($height/$thumb_height); 

    } 
    else { 
    // If the thumbnail is wider than the image 
    $new_width = $thumb_width; 
    $new_height = $height/($width/$thumb_width); 
    } 

    $thumb = imagecreatetruecolor($thumb_width, $thumb_height); 

    // Resize and crop 
    imagecopyresampled($thumb, 
     $image, 
     0 - ($new_width - $thumb_width)/2, // Center the image horizontally 
     0 - ($new_height - $thumb_height)/2, // Center the image vertically 
     0, 0, 
     $new_width, $new_height, 
     $width, $height); 
    imagejpeg($thumb, $filename, 80); 

} 
+0

Solución de trabajo fácil; pero compruebe primero el tipo de archivo y use imagecreatefrom jpg, png o gif puede ser un poco más útil. – web2kx

+0

cómo trabajar esto ... por favor ayúdame ... cómo mostrar como imagen – user3501407

3

Puede usar este código. Necesita pasar la ruta de la imagen de origen y el tamaño de la miniatura en px, y la ruta de destino opcional. si pasa, guardará la imagen; de lo contrario, se mostrará el pulgar.

Solo se permiten jpg, jpeg y png.

function cropImage($sourcePath, $thumbSize, $destination = null) { 

    $parts = explode('.', $sourcePath); 
    $ext = $parts[count($parts) - 1]; 
    if ($ext == 'jpg' || $ext == 'jpeg') { 
    $format = 'jpg'; 
    } else { 
    $format = 'png'; 
    } 

    if ($format == 'jpg') { 
    $sourceImage = imagecreatefromjpeg($sourcePath); 
    } 
    if ($format == 'png') { 
    $sourceImage = imagecreatefrompng($sourcePath); 
    } 

    list($srcWidth, $srcHeight) = getimagesize($sourcePath); 

    // calculating the part of the image to use for thumbnail 
    if ($srcWidth > $srcHeight) { 
    $y = 0; 
    $x = ($srcWidth - $srcHeight)/2; 
    $smallestSide = $srcHeight; 
    } else { 
    $x = 0; 
    $y = ($srcHeight - $srcWidth)/2; 
    $smallestSide = $srcWidth; 
    } 

    $destinationImage = imagecreatetruecolor($thumbSize, $thumbSize); 
    imagecopyresampled($destinationImage, $sourceImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide); 

    if ($destination == null) { 
    header('Content-Type: image/jpeg'); 
    if ($format == 'jpg') { 
     imagejpeg($destinationImage, null, 100); 
    } 
    if ($format == 'png') { 
     imagejpeg($destinationImage); 
    } 
    if ($destination = null) { 
    } 
    } else { 
    if ($format == 'jpg') { 
     imagejpeg($destinationImage, $destination, 100); 
    } 
    if ($format == 'png') { 
     imagepng($destinationImage, $destination); 
    } 
    } 
} 
+1

¿dónde está creando el pulgar? ¿Cuál es el camino del pulgar? escribe alguna descripción también –

+1

@PathikVejani gracias, he agregado una descripción. –

Cuestiones relacionadas