如果图像尺寸未知,则缩略图的大小必须相同

时间:2016-06-20 02:35:00

标签: php

我目前正在尝试为客户创建图库页面。我不希望客户端必须更改任何代码,所以我试图让我的图库从文件夹导入所有图像,并将它们全部显示为相同大小的缩略图。

我已经能够正确地获取/显示所有图像并打开灯箱,我的问题是很多缩略图都无法正常工作。我试图在保持纵横比的同时缩小图像,只是切掉多余的图像。似乎如果图像小于我为缩略图设置的尺寸,它可以正常工作,但如果图像大一点,它似乎只是将图像缩小到正确的宽度。这是一张显示我的意思的图片:

enter image description here

我真的不确定从哪里开始。

我最好保持宽高比

这是我的拇指功能:

function make_thumb($src,$dest,$desired_width, $desired_height, $ext) {
  $size=480;
  /* read the source image */
  if($ext == 'jpg' || $ext = 'jpeg') {
          $source_image = imagecreatefromjpeg($src);
  }
  if($ext == 'png') {
          $source_image = imagecreatefrompng($src);
  }
  $width = imagesx($source_image);
  $height = imagesy($source_image);

  $ratio = $width / $height;

  $targetWidth = $targetHeight = min($size, max($width, $height));

  if ($ratio < 1) {
      $targetWidth = $targetHeight * $ratio;
  } else {
      $targetHeight = $targetWidth / $ratio;
  }

  $srcWidth = $width;
  $srcHeight = $height;
  $srcX = $srcY = 0;

  $targetWidth = $targetHeight = min($width, $height, $size);

  if ($ratio < 1) {
      $srcX = 0;
      $srcY = ($height / 2) - ($width / 2);
      $srcWidth = $srcHeight = $width;
  } else {
      $srcY = 0;
      $srcX = ($width / 2) - ($height / 2);
      $srcWidth = $srcHeight = $height;
  }


  /* create a new, "virtual" image */
  $virtual_image = imagecreatetruecolor($targetWidth,$targetHeight);
  /* copy source image at a resized size */
  imagecopyresized($virtual_image,$source_image,0,0,$srcX,$srcY,$targetWidth,$targetHeight,$srcWidth,$srcHeight);
  /* create the physical thumbnail image to its destination */
  if($ext == 'jpg' || $ext = 'jpeg') {
          imagejpeg($virtual_image,$dest);
  }
  if($ext == 'png') {
          imagepng($virtual_image,$dest);
  }
}

1 个答案:

答案 0 :(得分:0)

我想出了我的问题。

首先,我有$ ext ='jpeg'而不是==

其次我不得不改变:

if ($ratio < 1) {
  $targetWidth = $targetHeight * $ratio;
} else {
  $targetHeight = $targetWidth / $ratio;
}

if ($ratio < 1) {
  $targetWidth = $targetHeight / $ratio;
} else {
  $targetHeight = $targetWidth / $ratio;
}