2009-10-05 92 views
0

我正在使用php和ajax。我可以從數據庫中檢索圖像,但我想以100px x 100px的大小顯示圖像,但它只是檢索原始圖像大小並破壞我所做的對齊工作。檢索圖像並將其加載到html頁面

如何修復檢索圖像的寬度和高度。我用下面的代碼從數據庫

$query = "select bin_data from imageupload where Id=1;"; 
$result = mysql_query($query, $con); 
$result_data = mysql_fetch_array($result, MYSQL_ASSOC); 
header("Content-type: image/jpeg") ; 
echo $result_data['bin_data']; 
+0

從數據庫本身回想起來,我想根據需要調整圖像大小 – praveenjayapal 2009-10-05 09:57:57

回答

0

您可以使用PHP的gd模塊做到這一點retriving。請參閱imagecopyresampled函數及其文檔中的示例。

請注意,這是一個昂貴的操作,因此您應該在上傳或緩存結果時保存已調整大小的圖像。

1

這些是此代碼執行步驟

  1. 複製源圖像
  2. 計算圖像尺寸
  3. 調整大小圖像(指定最大高度/寬度)
  4. 保留寬高比
  5. 寫入目的地圖片

這是從各種代碼片段創建的 我在這裏發現在php.net和其他地方在網絡上。
除了 將這些代碼放在一起之外,我對此代碼不加分。 http://www.php.net/manual/en/function.getimagesize.php

<?php 

$source_pic = 'images/source.jpg'; 
$destination_pic = 'images/destination.jpg'; 
$max_width = 500; 
$max_height = 500; 

$src = imagecreatefromjpeg($source_pic); 
list($width,$height)=getimagesize($source_pic); 

$x_ratio = $max_width/$width; 
$y_ratio = $max_height/$height; 

if(($width <= $max_width) && ($height <= $max_height)){ 
    $tn_width = $width; 
    $tn_height = $height; 
    }elseif (($x_ratio * $height) < $max_height){ 
     $tn_height = ceil($x_ratio * $height); 
     $tn_width = $max_width; 
    }else{ 
     $tn_width = ceil($y_ratio * $width); 
     $tn_height = $max_height; 
} 

$tmp=imagecreatetruecolor($tn_width,$tn_height); 
imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height); 

imagejpeg($tmp,$destination_pic,100); 
imagedestroy($src); 
imagedestroy($tmp); 

?> 
1

調整圖像大小是CPU密集型服務器,如果帶寬不是問題:

<img src="theimage.jpg" style="width:100px; height:100px;" /> 

現代瀏覽器過濾的圖像,調整大小,當它看起來很不錯。

它要保持寬高比和作物,做到這一點:

<div style="width:100px; height:100px; overflow:hidden; display:inline-block;"> 
    <img src="theimage.jpg" style="width:100px;" /> 
</div> 

還要考慮使用麪食的回答再加上圖像緩存。每張照片只能調整一次而不會丟失原稿。

相關問題