我想改变以下的PHP代码,以便它一次调整大小并显示一个图像,使用“下一个”和“上一个”按钮,以便浏览照片。我不想要任何图片库或灯箱解决方案,而是要在页面上显示的照片。我是php新手,所以如果有人可以提供帮助或指出我正确的方向,那么所有的帮助都会受到赞赏。
$sql = "select * from people";
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
while ($row = mysql_fetch_assoc($result))
{
echo "<div class=\"picture\">";
echo "<p>";
// Note that we are building our src string using the filename from the database
echo "<img src=\"images/" . $row['filename'] . "\" alt=\"\" /><br />";
echo $row['fname'] . " " . $row['lname'] . "<br />";
echo "</p>";
echo "</div>";
答案 0 :(得分:1)
您可以使用width
和height
属性在浏览器中对其进行缩放(或者只保留一个属性)但是这很糟糕,包括带宽,页面性能和图像质量等。
IMagick
的快速示例:
$hThumb = new Imagick($path_to_file); // Source file
$hThumb->thumbnailImage($x, $y); // You can use 300, 0 to do 300 width and maintain aspect ratio.
$hThumb->stripImage(); // remove meta data
$hThumb->writeImage($path_to_thumb); // write the image to disk
注意强>
确保具有读/写权限。您可以使用is_readable
和is_writable
验证此权限。
<强>载入强>
建议使用AJAX
加载图像,如果使用JQuery
或类似的库,则非常容易。
$('#nextBtn').click(function() {
var index = 0; // Store this in your image ID tag perhaps
// e.g. $('#theImage').attr('id').replace('image', '')
// where ID is imageX
$.ajax({
url: 'getImages.php?index=' + index,
type: "GET",
success: function(data) {
var result = $.parseJSON(data);
if (result.success) {
// Set your image src with the new path.
// Use result.image_data.src etc...
}
}
});
});
PHP也会相对简单,结构类似于:
<?php
$return = array('success' => false, 'image_data' => array());
if (isset($_GET['index']) && is_numeric($_GET['index')) {
// Fetch your image
$return = array(
'success' => true,
'image_data' => array(
'src' => $src,
'title' => $title,
'index' => $index
)
);
}
echo json_encode($return);
?>
**另一个注意事项**
正如kgb所述,您应该在上传时调整这些值,但是,它们可能不是用户提交的,因此您还可以检查输出上是否存在拇指并根据需要生成任何拇指。当然,不要为每个视图生成它们。
答案 1 :(得分:1)
您应该在上传时调整图像大小,而不是在输出上调整大小。存储原始图像和已调整大小的图像,在列表中显示小图像,并在用户需要时显示完整尺寸...
来自imagecopyresampled()文档的示例代码:
// Get new dimensions
list($width, $height) = getimagesize($filename);
$widthNew = 320; // You decide
$heightNew = 240; // You decide
// Resample
$imageNew = imagecreatetruecolor($widthNew, $heightNew);
$imageOld = imagecreatefromjpeg($filename);
imagecopyresampled($imageNew, $imageOld, 0, 0, 0, 0, $widthNew, $heightNew, $width, $height);
// Output
imagejpeg($imageNew, $newFilename, 100);
此示例期望gd扩展包含在php中。 Martin提到的Imagick扩展功能更强大,提供更好的界面,但很少包含在网络托管中。
也为您搜索了这个:http://www.9lessons.info/2009/03/upload-and-resize-image-with-php.html