使用 PHP 创建缩略图。 (裁剪成正方形)

问题描述 投票:0回答:5

我目前正在使用一个 php 脚本,它根据最大宽度和高度创建缩略图。但是,我希望它始终创建方形图像并在需要时裁剪图像。

这是我现在正在使用的:

    function makeThumb( $filename, $type ) {
  global $max_width, $max_height;
  if ( $type == 'jpg' ) {
   $src = imagecreatefromjpeg("blocks/img/gallery/" . $filename);
  } else if ( $type == 'png' ) {
   $src = imagecreatefrompng("blocks/img/gallery/" . $filename);
  } else if ( $type == 'gif' ) {
   $src = imagecreatefromgif("blocks/img/gallery/" . $filename);
  }
  if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) {
   $newW = $oldW * ($max_width / $oldH);
   $newH = $max_height;
  } else {
   $newW = $max_width;
   $newH = $oldH * ($max_height / $oldW);
  }
  $new = imagecreatetruecolor($newW, $newH);
  imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH);
  if ( $type == 'jpg' ) {
   imagejpeg($new, 'blocks/img/gallery/thumbs/'.$filename);
  } else if ( $type == 'png' ) {
   imagepng($new, 'blocks/img/gallery/thumbs/'.$filename);
  } else if ( $type == 'gif' ) {
   imagegif($new, 'blocks/img/gallery/thumbs/'.$filename);
  }
  imagedestroy($new);
  imagedestroy($src);
 }

我将如何改变它来实现我想要的(方形拇指)?

提前致谢。

php image thumbnails
5个回答
16
投票
function makeThumb( $filename , $thumbSize=100 ){
  global $max_width, $max_height;
 /* Set Filenames */
  $srcFile = 'blocks/img/gallery/'.$filename;
  $thumbFile = 'blocks/img/gallery/thumbs/'.$filename;
 /* Determine the File Type */
  $type = substr( $filename , strrpos( $filename , '.' )+1 );
 /* Create the Source Image */
  switch( $type ){
    case 'jpg' : case 'jpeg' :
      $src = imagecreatefromjpeg( $srcFile ); break;
    case 'png' :
      $src = imagecreatefrompng( $srcFile ); break;
    case 'gif' :
      $src = imagecreatefromgif( $srcFile ); break;
  }
 /* Determine the Image Dimensions */
  $oldW = imagesx( $src );
  $oldH = imagesy( $src );
 /* Calculate the New Image Dimensions */
  $limiting_dim = 0;
  if( $oldH > $oldW ){
   /* Portrait */
    $limiting_dim = $oldW;
  }else{
   /* Landscape */
    $limiting_dim = $oldH;
  }
 /* Create the New Image */
  $new = imagecreatetruecolor( $thumbSize , $thumbSize );
 /* Transcribe the Source Image into the New (Square) Image */
  imagecopyresampled( $new , $src , 0 , 0 , ($oldW-$limiting_dim )/2 , ( $oldH-$limiting_dim )/2 , $thumbSize , $thumbSize , $limiting_dim , $limiting_dim );
  switch( $type ){
    case 'jpg' : case 'jpeg' :
      $src = imagejpeg( $new , $thumbFile ); break;
    case 'png' :
      $src = imagepng( $new , $thumbFile ); break;
    case 'gif' :
      $src = imagegif( $new , $thumbFile ); break;
  }
  imagedestroy( $new );
  imagedestroy( $src );
}

@Sam Wan致敬以获取调整后的解决方案。抱歉,我花了这么长时间才将其合并到这个答案中。


15
投票
   /* Calculate the New Image Dimensions */
   $limiting_dim = 0;
    if( $oldH > $oldW ){
     /* Portrait */
      $limiting_dim = $oldW;
    }else{
     /* Landscape */
      $limiting_dim = $oldH;
    }
   /* Create the New Image */
    $new = imagecreatetruecolor( $thumbSize , $thumbSize );
   /* Transcribe the Source Image into the New (Square) Image */
    imagecopyresampled( $new , $src , 0 , 0 , ($oldW-$limiting_dim )/2 , ( $oldH-$limiting_dim )/2 , $thumbSize , $thumbSize , $limiting_dim , $limiting_dim );

我没有足够的业力来评论已接受的答案(Lucanos'),但我发现上面的答案在缩略图的一侧出现了黑条。

此代码片段(与接受的答案相结合)应复制 src 图像的相关部分,而不会超出范围并产生黑条。按照原来的问题,缩略图仍然是方形的。


2
投票

您想要计算出偏移量而不是新的宽度/高度,以便新样本保持比例,然后在生成新图像时使用偏移量并为其指定固定的宽度/高度,以便它将裁剪为正方形。一个可以制作 100x100 拇指的简单示例(注意:未经测试),

// Get dimensions of the src image.
list($oldW, $oldH) = getimagesize($filename);

// Work out what offset to use
if ($oldH < $oldW) 
{
    $offH = 0;
    $offW = ($oldW-$oldH)/2;
    $oldW = $oldH;
} 
elseif ($oldH > $oldW) 
{
    $offW = 0;
    $offH = ($oldH-$oldW)/2;
    $oldH = $oldW;
} 
else 
{
    $offW = 0;
    $offH = 0;
}                

// Resample the image into the new dimensions.
$new = imagecreatetruecolor(100, 100);
imagecopyresampled($new, $src, 0, 0, $offW, $offH, 100, 100, $oldW, $oldH);

0
投票

这个修改后的功能对我来说非常有用

public function igImagePrepare($img,$name){
    $dir = 'my-images/';
    $img_name = $name.'-'.uniqid().'.jpg';

    //Your Image
    $imgSrc = $img;

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

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

    $square_size = 400;

    $width = imagesx( $myImage );
    $height = imagesy( $myImage );


                //set dimensions
                if($width> $height) {
                        $width_t=$square_size;
                        //respect the ratio
                        $height_t=round($height/$width*$square_size);
                        //set the offset
                        $off_y=ceil(($width_t-$height_t)/2);
                        $off_x=0;
                } elseif($height> $width) {
                        $height_t=$square_size;
                        $width_t=round($width/$height*$square_size);
                        $off_x=ceil(($height_t-$width_t)/2);
                        $off_y=0;
                }
                else {
                        $width_t=$height_t=$square_size;
                        $off_x=$off_y=0;
                }


   /* Create the New Image */
    $new = imagecreatetruecolor( $square_size , $square_size );
   /* Transcribe the Source Image into the New (Square) Image */
    $bg = imagecolorallocate ( $new, 255, 255, 255 );
    imagefill ( $new, 0, 0, $bg );
    imagecopyresampled( $new , $myImage , $off_x, $off_y, 0, 0, $width_t, $height_t, $width, $height );

    //final output
    imagejpeg($new, $dir.$img_name);

    return $dir.$img_name;
  }

0
投票

由于我们这里有多个部分解决方案(归功于Luke StevensonSam Wan),我觉得有必要将这些部分组合在一起。这是两个答案加上一些附加功能的完整解决方案:

  • 其他函数参数,例如基本 + 拇指目录名称。

  • 覆盖布尔参数,以便在缩略图已经存在时快速加载页面。

  • 检查thumb目录是否存在;如果没有,则创建。

  • 修复了

    imagedestroy($src);
    问题。

/**
 * Function to create a thumbnail of an image.
 * See https://stackoverflow.com/questions/2686000/use-php-to-create-thumbnails-cropped-to-square
 * @param $basePath
 * @param $filename
 * @param string $thumbDirName
 * @param int $thumbSize
 * @param bool $overwrite
 * @return bool|null
 */
function makeThumb($basePath, $filename, $thumbDirName = 'thumbs', $thumbSize = 150, $overwrite = false)
{
    /* Configure paths. */
    $basePath = rtrim($basePath, '/') . '/';
    $thumbDirName = trim($thumbDirName, '/') . '/';
    $srcFile = $basePath . $filename;
    $thumbBasePath = $basePath . $thumbDirName;
    
    if (!is_dir($thumbBasePath)) {
        if(!mkdir($thumbBasePath, 0755)){
            throw new RuntimeException('could not create thumb dir: ' . $thumbBasePath);
        }
    }
    
    $thumbServerPath = $thumbBasePath . $filename;
    if(!$overwrite){
        /* Check if thumbnail exists already. */
        if(file_exists($thumbServerPath)){
            return null;
        }
    }

    /* Determine the File Type */
    $type = substr($filename, strrpos($filename, '.') + 1);
    /* Create the Source Image */
    switch ($type) {
        case 'jpg' :
        case 'jpeg' :
            $src = imagecreatefromjpeg($srcFile);
            break;
        case 'png' :
            $src = imagecreatefrompng($srcFile);
            break;
        case 'gif' :
            $src = imagecreatefromgif($srcFile);
            break;
        default:
            return false;
    }
    /* Determine the Image Dimensions */
    $oldW = imagesx($src);
    $oldH = imagesy($src);

    /* Calculate the New Image Dimensions */
    $limiting_dim = $oldH; /* Landscape */
    if( $oldH > $oldW ){
        $limiting_dim = $oldW; /* Portrait */
    }

    /* Create the New Image */
    $new = imagecreatetruecolor( $thumbSize , $thumbSize );

    /* Transcribe the Source Image into the New (Square) Image */
    imagecopyresampled( $new , $src , 0 , 0 , ($oldW-$limiting_dim )/2 , ( $oldH-$limiting_dim )/2 , $thumbSize , $thumbSize , $limiting_dim , $limiting_dim );

    switch ($type) {
        case 'jpg' :
        case 'jpeg' :
            imagejpeg($new, $thumbServerPath);
            break;
        case 'png' :
            imagepng($new, $thumbServerPath);
            break;
        case 'gif' :
            imagegif($new, $thumbServerPath);
            break;
    }
    imagedestroy($new);
    imagedestroy($src);

    return true;
}
© www.soinside.com 2019 - 2024. All rights reserved.