我在调整Blob图片大小时遇到一个小问题.
我发现我必须做BLOB的高度和宽度,但是由于人们上传的图像不是正方形,如何正确调整它们的大小?
基本上我希望最大宽度为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);
解决方法:
保留约束比例的一种调整图像大小的简单方法:
<?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);
?>