2010-01-05 26 views
15

Me gustaría recortar una imagen en PHP y guardar el archivo. Sé que se supone que debes usar la biblioteca de GD, pero no estoy seguro de cómo. ¿Algunas ideas?Recortar imagen en PHP

Gracias

Respuesta

23

Usted podría utilizar imagecopy para recortar una parte necesaria de una imagen. El comando es la siguiente:

imagecopy ( 
    resource $dst_im - the image object , 
    resource $src_im - destination image , 
    int $dst_x - x coordinate in the destination image (use 0) , 
    int $dst_y - y coordinate in the destination image (use 0) , 
    int $src_x - x coordinate in the source image you want to crop , 
    int $src_y - y coordinate in the source image you want to crop , 
    int $src_w - crop width , 
    int $src_h - crop height 
) 

Código de PHP.net - una imagen de 80x40 píxeles se recorta una imagen de origen

<?php 
// Create image instances 
$src = imagecreatefromgif('php.gif'); 
$dest = imagecreatetruecolor(80, 40); 

// Copy 
imagecopy($dest, $src, 0, 0, 20, 13, 80, 40); 

// Output and free from memory 
header('Content-Type: image/gif'); 
imagegif($dest); 

imagedestroy($dest); 
imagedestroy($src); 
?> 
+0

Gracias por la respuesta rápida !! – user244228

+0

¿Demasiado este método para agregar fondo negro a las imágenes PNG? Quiero decir sobre el fondo transparente? – bayblade567

1

de Para recortar una imagen con GD es necesario utilizar una combinación de métodos GD, y si observa el "Ejemplo n. ° 1" en la documentación de PHP del método imagecopyresampled, le muestra cómo recortar y generar una imagen, solo necesita agregar algún código para capturar y escribir la salida en un archivo.

http://us2.php.net/manual/en/function.imagecopyresampled.php

También existen otras opciones, incluyendo Image Magick que, de ser instalado en el servidor, se puede acceder directamente a través de exec método de PHP (o similar) o puede instalar la extensión PHP Imagick, que produce imágenes de mayor calidad y, en mi opinión es un poco más intuitiva y flexible para trabajar.

Finalmente, he usado la biblioteca de clases de código abierto PHPThumb, que tiene una interfaz bastante simple y puede trabajar con múltiples opciones dependiendo de lo que hay en tu servidor, incluyendo ImageMagick y GD.

0

Yo uso este script en algunos proyectos y es bastante fácil de usar: http://shiftingpixel.com/2008/03/03/smart-image-resizer/

El script requiere PHP 5.1.0 (que está fuera desde 2005-11-24 - hora de actualizar, si aún no en este versión) y GD (que rara vez falta de buenos servidores web).

Aquí es un ejemplo de su uso en el código HTML:

<img src="/image.php/coffee-bean.jpg?width=200&amp;height=200&amp;image=/wp-content/uploads/2008/03/coffee-bean.jpg" alt="Coffee Bean" /> 
+0

shiftingpixel.com parece estar por el momento, intente el enlace más tarde :) – AlexV

+0

shiftingpixel.com ha vuelto :) – AlexV

3

Esta función será recortar la imagen manteniendo la relación de aspecto :)

function resize_image_crop($image, $width, $height) 
    { 

     $w = @imagesx($image); //current width 

     $h = @imagesy($image); //current height 
     if ((!$w) || (!$h)) { $GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.'; return false; } 
     if (($w == $width) && ($h == $height)) { return $image; } //no resizing needed 
     $ratio = $width/$w;  //try max width first... 
     $new_w = $width; 
     $new_h = $h * $ratio;  
     if ($new_h < $height) { //if that created an image smaller than what we wanted, try the other way 
      $ratio = $height/$h; 
      $new_h = $height; 
      $new_w = $w * $ratio; 
     } 
     $image2 = imagecreatetruecolor ($new_w, $new_h); 
     imagecopyresampled($image2,$image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);  
     if (($new_h != $height) || ($new_w != $width)) { //check to see if cropping needs to happen 
      $image3 = imagecreatetruecolor ($width, $height); 
      if ($new_h > $height) { //crop vertically 
       $extra = $new_h - $height; 
       $x = 0; //source x 
       $y = round($extra/2); //source y 
       imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height); 
      } else { 
       $extra = $new_w - $width; 
       $x = round($extra/2); //source x 
       $y = 0; //source y 
       imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height); 
      } 
      imagedestroy($image2); 
      return $image3; 
     } else { 
      return $image2; 
     } 
    } 
+0

No debería tener que hacer múltiples llamadas impresas por imágenes, todo se puede hacer en una llamada si el desplazamiento se calcula en $ ancho y $ altura. Además, podría ser preferible forzar siempre el cambio de tamaño para garantizar que la imagen se guarde en un nuevo formato sin basura adicional y con encabezados y forzada a una calidad específica. – Exit

-1

Puede utilizar a continuación el método cultivos de imágenes a,

/*parameters are 
    $image =source image name 
    $width = target width 
    $height = height of image 
    $scale = scale of image*/ 
    function resizeImage($image,$width,$height,$scale) { 
     //generate new image height and width of source image 
     $newImageWidth = ceil($width * $scale); 
     $newImageHeight = ceil($height * $scale); 
     //Create a new true color image 
     $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight); 
     //Create a new image from file 
     $source = imagecreatefromjpeg($image); 
     //Copy and resize part of an image with resampling 
     imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height); 
     //Output image to file 
     imagejpeg($newImage,$image,90); 
     //set rights on image file 
     chmod($image, 0777); 
     //return crop image 
     return $image; 
    } 
+0

Puede ser útil para los usuarios si agrega comentarios a su código para explicar qué hacen las partes clave. Esto les ayudaría a comprender mejor y aplicar su código – shrmn

+0

ok, he añadido –

0

Acabo de crear esta función y funciona para mis necesidades, creando un centro y recortada imagen en miniatura. Se simplifica y no requiere múltiples llamadas a imágenes como se muestra en la respuesta de webGautam.

Proporcione la ruta de la imagen, el ancho y el alto finales, y opcionalmente la calidad de la imagen. Hice esto para crear miniaturas, por lo que todas las imágenes se guardan como JPG, puede editarlas para acomodar otros tipos de imágenes si las necesita. El punto principal aquí es la matemática y el método de usar imagecopyresampleado para producir una miniatura. Las imágenes se guardan con el mismo nombre, más el tamaño de la imagen.

function resize_crop_image($image_path, $end_width, $end_height, $quality = '') { 
if ($end_width < 1) $end_width = 100; 
if ($end_height < 1) $end_height = 100; 
if ($quality < 1 || $quality > 100) $quality = 60; 

$image = false; 
$dot = strrpos($image_path,'.'); 
$file = substr($image_path,0,$dot).'-'.$end_width.'x'.$end_height.'.jpg'; 
$ext = substr($image_path,$dot+1); 

if ($ext == 'jpg' || $ext == 'jpeg') $image = @imagecreatefromjpeg($image_path); 
elseif($ext == 'gif') $image = @imagecreatefromgif($image_path); 
elseif($ext == 'png') $image = @imagecreatefrompng($image_path); 

if ($image) { 
    $width = imagesx($image); 
    $height = imagesy($image); 
    $scale = max($end_width/$width, $end_height/$height); 
    $new_width = floor($scale*$width); 
    $new_height = floor($scale*$height); 
    $x = ($new_width != $end_width ? ($width - $end_width)/2 : 0); 
    $y = ($new_height != $end_height ? ($height - $end_height)/2 : 0); 
    $new_image = @imagecreatetruecolor($new_width, $new_height); 

    imagecopyresampled($new_image,$image,0,0,$x,$y,$new_width,$new_height,$width - $x,$height - $y); 
    imagedestroy($image); 
    imagejpeg($new_image,$file,$quality); 
    imagedestroy($new_image); 

    return $file; 
} 
return false; 
} 
Cuestiones relacionadas