2009-10-05 95 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> 

还要考虑使用面食的回答再加上图像缓存。每张照片只能调整一次而不会丢失原稿。

相关问题