php实现显示图片
显示本地图片
在PHP中显示本地存储的图片,可以通过读取文件并设置正确的HTTP头来实现。以下是一个简单的示例:
<?php
$imagePath = 'path/to/your/image.jpg';
if(file_exists($imagePath)) {
$mimeType = mime_content_type($imagePath);
header('Content-Type: '.$mimeType);
readfile($imagePath);
} else {
header('HTTP/1.0 404 Not Found');
echo 'Image not found';
}
?>
从数据库显示图片
当图片存储在数据库中时,通常以BLOB形式保存。以下是显示数据库图片的示例:
<?php
// 假设已经建立了数据库连接$conn
$imageId = $_GET['id'] ?? 0;
$stmt = $conn->prepare("SELECT image_data, image_type FROM images WHERE id = ?");
$stmt->bind_param("i", $imageId);
$stmt->execute();
$result = $stmt->get_result();
if($row = $result->fetch_assoc()) {
header('Content-Type: '.$row['image_type']);
echo $row['image_data'];
} else {
header('HTTP/1.0 404 Not Found');
echo 'Image not found';
}
?>
在HTML中嵌入图片
更常见的方式是在HTML中通过img标签引用PHP生成的图片:
<img src="show_image.php?id=123" alt="Example Image">
对应的show_image.php文件内容类似于上面的数据库显示示例。
图片缩略图生成
使用GD库创建缩略图并显示:
<?php
$sourceImage = 'original.jpg';
$thumbnailWidth = 200;
list($width, $height) = getimagesize($sourceImage);
$ratio = $height/$width;
$thumbnailHeight = $thumbnailWidth * $ratio;
$image = imagecreatefromjpeg($sourceImage);
$thumbnail = imagecreatetruecolor($thumbnailWidth, $thumbnailHeight);
imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $thumbnailWidth, $thumbnailHeight, $width, $height);
header('Content-Type: image/jpeg');
imagejpeg($thumbnail);
imagedestroy($image);
imagedestroy($thumbnail);
?>
图片水印添加
为图片添加文字水印并显示:
<?php
$image = imagecreatefromjpeg('original.jpg');
$textColor = imagecolorallocate($image, 255, 255, 255);
imagettftext($image, 20, 0, 10, 30, $textColor, 'arial.ttf', 'Watermark Text');
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
?>
图片缓存控制
为了提高性能,可以添加缓存控制头:
header('Content-Type: image/jpeg');
header('Cache-Control: max-age=86400');
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
readfile('image.jpg');
安全注意事项
处理用户提供的图片时需要注意安全:

- 验证文件类型
- 限制访问目录
- 防止路径遍历攻击
- 对上传文件进行病毒扫描
$allowedTypes = ['image/jpeg', 'image/png'];
$mimeType = mime_content_type($imagePath);
if(!in_array($mimeType, $allowedTypes)) {
die('Invalid image type');
}






