2016-06-20 218 views
1

我正在嘗試爲客戶端創建圖庫頁面。我不希望客戶端必須更改任何代碼,所以我試圖讓我的畫廊從文件夾中導入所有圖像,並將它們全部顯示爲相同尺寸的縮略圖。如果圖像尺寸未知,請縮略圖大小相同

我已經能夠正確提取/顯示所有圖像並打開燈箱,我的問題是很多縮略圖無法正常工作。我試圖在保持高寬比的同時縮小圖像,並且只是剪掉多餘的圖像。看起來,如果圖像的尺寸小於我爲縮略圖設置的尺寸,它可以正常工作,但如果尺寸較大,它似乎會將圖像縮放到正確的寬度。下面是說明我的意思的圖像:

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

爲什麼你不使用'add_image_size(」名稱',寬度,高度,真)' – deemi

+0

我的印象是add_images_size()是wordpress嗎? –

回答

0

我想通了,我的問題。

首先,我不得不$分機= 'JPEG',而不是==

其次,我不得不改變:

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

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