2011-05-22 39 views
3

我有一個小問題重新調整大小圖像。 我發現的是我必須做BLOB的高度和寬度,但因爲人們上傳的圖像不是方形的,我該如何重新調整它們的大小?BLOB - PHP重新大小圖像

基本上我想要的最大寬度爲300px;

我當前的代碼是

$desired_width = 300; 
$desired_height = 300; 

$sth = mysql_query("SELECT photobase FROM userpictures WHERE id = '".$array[0]."'"); 

while($r = mysql_fetch_assoc($sth)) { 
     $blobcontents = $r["photobase"]; 

     $im = imagecreatefromstring($blobcontents); 
     $new = imagecreatetruecolor($desired_width, $desired_height); 

     $x = imagesx($im); 
     $y = imagesy($im); 

     imagecopyresampled($new, $im, 0, 0, 0, 0, $desired_width, $desired_height, $x, $y); 

     imagedestroy($im); 

     header('Content-type: <span class="posthilit">image</span>/jpeg'); 

     imagejpeg($new, null, 85); 

回答

3

一個簡單的方法來調整一個圖像保持約束比例:

<?php 
// Constraints 
$max_width = 100; 
$max_height = 100; 
list($width, $height) = getimagesize($img_path); 
$ratioh = $max_height/$height; 
$ratiow = $max_width/$width; 
$ratio = min($ratioh, $ratiow); 
// New dimensions 
$width = intval($ratio*$width); 
$height = intval($ratio*$height); 
?> 
+0

謝謝你這麼這麼這麼多 – RussellHarrower 2011-05-22 12:37:29

+0

什麼BLOB在這種情況下'和getimagesize($ img_path)'是不是需要一個文件路徑,而不是文件內容? – Tiny 2016-06-13 12:01:14