2013-05-23 3 views
-1

У меня есть изображение и все необходимые размеры для обрезки изображения. Я хочу выбрать изображение из исходного пути и сохранить изображение в путь назначения. Я хочу знать, какие функции в PHP должны Я использую, чтобы обрезать изображение и сохранить его.Обрезать изображение, если размеры известны

+0

Начало глядя на PHP инструкции: http://ca.php.net/manual/en/book.imagick.php –

+0

Это может быть полезно: http://stackoverflow.com/questions/1855996/crop-image-in-php –

ответ

3

The follwing code will do the work

/** 
* Php function to crop an image 
* 
* @param string $source_image Path of the source image 
* @param string $target_image Path of the target image 
* @param array $crop_area Array like array('left' => [LEFT], 'top' => [TOP], 
*           'width' => [WIDTH], => 'height' => [HEIGHT]) 
*/ 
function cropImage($source_image, $target_image, $crop_area) 
{ 
    // detect source image type from extension 
    $source_file_name = basename($source_image); 
    $source_image_type = substr($source_file_name, -3, 3); 

    // create an image resource from the source image 
    switch(strtolower($source_image_type)) 
    { 
     case 'jpg': 
      $original_image = imagecreatefromjpeg($source_image); 
      break; 

     case 'gif': 
      $original_image = imagecreatefromgif($source_image); 
      break; 

     case 'png': 
      $original_image = imagecreatefrompng($source_image); 
      break;  

     default: 
      trigger_error('cropImage(): Invalid source image type', E_USER_ERROR); 
      return false; 
    } 

    // create a blank image having the same width and height as the crop area 
    // this will be our cropped image 
    $cropped_image = imagecreatetruecolor($crop_area['width'], $crop_area['height']); 

    // copy the crop area from the source image to the blank image created above 
    imagecopy($cropped_image, $original_image, 0, 0, $crop_area['left'], $crop_area['top'], 
       $crop_area['width'], $crop_area['height']); 

    // detect target image type from extension 
    $target_file_name = basename($target_image); 
    $target_image_type = substr($target_file_name, -3, 3); 

    // save the cropped image to disk 
    switch(strtolower($target_image_type)) 
    { 
     case 'jpg': 
      imagejpeg($cropped_image, $target_image, 100); 
      break; 

     case 'gif': 
      imagegif($cropped_image, $target_image); 
      break; 

     case 'png': 
      imagepng($cropped_image, $target_image, 0); 
      break;  

     default: 
      trigger_error('cropImage(): Invalid target image type', E_USER_ERROR); 
      imagedestroy($cropped_image); 
      imagedestroy($original_image); 
      return false; 
    } 

    // free resources 
    imagedestroy($cropped_image); 
    imagedestroy($original_image); 

    return true; 
} 


// using the function to crop an image 
$source_image = 'image.jpg'; 
$target_image = 'cropped_image.jpg'; 
$crop_area = array('top' => 100, 'left' => 100, 'height' => 300, 'width' => 300); 

cropImage($source_image, $target_image, $crop_area); 

ИЛИ See this

+0

Спасибо .. Он работает. – Happy

1

Попробуйте эту функцию, он генерирует новое изображение в размерах указанных вами, сохраняя пропорции и croping изображения, когда это необходимо.

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; 
    } 
} 
Смежные вопросы