2011-03-15 4 views
2

Я использую эту функциюИзменить размер изображения по шкале?

function resize($width,$height) { 

    $new_image = imagecreatetruecolor($width, $height); 

    imagesavealpha($new_image, true); 
    $trans_colour = imagecolorallocatealpha($new_image, 0, 0, 0, 127); 
    imagefill($new_image, 0, 0, $trans_colour); 

    imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); 
    $this->image = $new_image; 
} 

То, что я хочу сделать, это квадратное изображение. Я хотел бы изменить размер по наименьшему атрибуту, а затем вместо большого числа. Я бы хотел, чтобы края отрубили.

Так что, если у меня есть изображение, которое 213 х 180, который мне нужен уменьшенный до 150 х 150

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

То, что я не знаю, как это сделать, - это взять ширину и отрубить края, чтобы получить ширину 150 без искажений.

Кто-нибудь знает, как это сделать?

+0

Итак, вы хотите, чтобы обрезать площадь изображения перед его размера? Почему бы не изменить размер поддерживающего пропорции, а затем обрезать, размер которого больше 150? – Treffynnon

+1

Если вы не хотите возиться с низкоуровневыми операциями с изображениями, настоятельно рекомендуется широкоформатная библиотека (http://wideimage.sourceforge.net/). –

ответ

2

К «Отрубите» край я предполагаю, что вы имеете в виду сделать урожай вы изображения, не так ли?

Для получения изображения вы можете использовать imagecopyresized.

Небольшой пример:

$imageSrc = //Your source image; 
$tempImage = imagecreatetruecolor(150,150); 
// CropStartX et cropStartY have to be computed to suit your needs 
imagecopyresized($tempImage,$imageSrc,0,0,$cropStartX,$cropStartY,150,150,150,150); 
// $tempImage now contain your cropped image. 
2

Это скопировано из старого проекта шахты, делает то, что вам нужно:

static public function resizeCropAndMove($from_path, $to_path, $max_width, $max_height) 
    { 
    $image_info = getImageSize($from_path); 
    switch ($image_info['mime']) { 
     case 'image/jpeg': $input = imageCreateFromJPEG($from_path); break; 
     default: 
     return false; 
    } 

    $input_width = imagesx($input); 
    $input_height = imagesy($input); 

    $output = imageCreateTrueColor($max_width, $max_height); 

    if ($input_width <= $input_height) { //portrait 
    $lamda = $max_width/$input_width; 

    if ($lamda < 1) { 
     $temp_width = (int)round($lamda * $input_width); 
     $temp_height = (int)round($lamda * $input_height); 

     $temp = imagecreatetruecolor($temp_width, $temp_height); 
     imageCopyResampled($temp, $input, 0, 0, 0, 0, $temp_width, $temp_height, $input_width, $input_height); 

     $top = (int)round(($temp_height - $max_height)/2); 
     $left = 0; 
    }  
    } else { //landscape 
    $lamda = $max_height/$input_height; 

    if ($lamda < 1) { 
     $temp_width = (int)round($lamda * $input_width); 
     $temp_height = (int)round($lamda * $input_height); 

     $temp = imagecreatetruecolor($temp_width, $temp_height); 
     imageCopyResampled($temp, $input, 0, 0, 0, 0, $temp_width, $temp_height, $input_width, $input_height); 

     $left = (int)round(($temp_width - $max_width)/2); 
     $top = 0; 
    } 
    } 

    if ($lamda < 1) { 
    imageCopyResampled($output, $temp, 0, 0, $left, $top, $max_width, $max_height, $max_width, $max_height); 
    imagePNG($output, $to_path); 
    imagedestroy($temp); 
    } else { 
    imagePNG($input, $to_path); 
    } 

    imageDestroy($input); 
    imageDestroy($output); 
    } 
2
function createCroppedThumb($thumbSourcePath, $thumbSavePath, $thumbDim){ 

     // Get dimensions of the original image 
     $detail    = getimagesize($thumbSourcePath); 
     $current_width  = $detail[0]; 
     $current_height  = $detail[1]; 
     $imageType   = $detail[2]; 

     // The x and y coordinates on the original image where we 
     // will begin cropping the image 
     $left = 0; 
     $top = 0; 

     // This will be the final size of the image (e.g. how many pixels 
     // left and down we will be going) 
     $crop_width  = $thumbDim; 
     $crop_height = $thumbDim; 

     // Resample the image 
     $canvas = imagecreatetruecolor($crop_width, $crop_height); 

     switch($imageType){ 
      case '1': 
      $current_image = imagecreatefromgif($thumbSourcePath); 
      break; 

      case '2': 
      $current_image = imagecreatefromjpeg($thumbSourcePath); 
      break; 

      case '3': 
      $current_image = imagecreatefrompng($thumbSourcePath); 
      break; 

      default: 
      throw new Exception('unknown image type'); 
      break;  
     } 
     imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height); 

     switch($imageType){ 
      case '1': 
      imagegif($canvas,$thumbSavePath,100); 
      break; 

      case '2': 
      imagejpeg($canvas,$thumbSavePath,100); 
      break; 

      case '3': 
      imagepng($canvas,$thumbSavePath,100); 
      break; 

      default: 
      throw new Exception('unknown image type'); 
      break;  
     } 
} 
Смежные вопросы