调整图像大小(image_lib),保持纵横比,但可以缩放到SMALLEST,超出宽度和高度

时间:2012-03-18 12:23:20

标签: php codeigniter

所以我想拍一张方形图像并将其调整为300px * 400px(例如)。

我想保持纵横比,但是图片超出或匹配两个尺寸。因此,对于方形原始图像,生成的图像将为400px * 400px。

这有意义吗?我想要这个,因为那时我将继续将图像裁剪为300px * 400px。

设置$config['maintain_ratio'] = false;会扭曲图像。

感谢您的任何启发。

1 个答案:

答案 0 :(得分:2)

试试这个....这会有所帮助..

    if(file_exists('test.jpg'))
         unlink('test.jpg');

       $dest='test.jpg';


  $image='fg.jpg';

 $list=getimagesize($image);
 $width=$list[0];
  $height=$list[1];


   $newwidth=65;
    $newheight=95;



   $int_x=10;
 $int_y=0;




define( 'DESIRED_IMAGE_WIDTH', 65 );
define( 'DESIRED_IMAGE_HEIGHT', 95 );
$source_gdim = imagecreatefromjpeg($image);

$source_aspect_ratio = $width / $height;
$desired_aspect_ratio = DESIRED_IMAGE_WIDTH / DESIRED_IMAGE_HEIGHT;

 // For Wide Image
if ( $source_aspect_ratio > $desired_aspect_ratio )
  {
$temp_height = DESIRED_IMAGE_HEIGHT;
$temp_width = ( int ) ( DESIRED_IMAGE_HEIGHT * $source_aspect_ratio );
  }
  // For Tall Image
else
  {
  $temp_width = DESIRED_IMAGE_WIDTH;
   $temp_height = ( int ) ( DESIRED_IMAGE_WIDTH / $source_aspect_ratio );
   }


   $temp_gdim = imagecreatetruecolor( $temp_width, $temp_height );
  imagecopyresampled($temp_gdim,$source_gdim,0, 0,0, 0,$temp_width, $temp_height,$width, $height);


 $x0 = ( $temp_width - DESIRED_IMAGE_WIDTH ) / 2;
  $y0 = ( $temp_height - DESIRED_IMAGE_HEIGHT ) / 2;

  $desired_gdim = imagecreatetruecolor( DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT );
    imagecopy($desired_gdim,$temp_gdim,0, 0,$x0, $y0,DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT);


      imagejpeg( $desired_gdim,'test.jpg',100 );