1. Header函数简介
header("Content-type: image/jpeg");
上述代码设置了内容类型为JPEG图像。
2. 设置正确的Content-type
- GIF图像:
Content-type: image/gif
- JPEG图像:
Content-type: image/jpeg
- PNG图像:
Content-type: image/png
3. 避免重复调用Header函数
// 错误的示例
header("Content-type: image/jpeg");
echo "<img src='image.jpg' />";
header("Content-type: image/jpeg");
4. 输出图片
<?php
// 加载图像
$image = imagecreatefromjpeg("image.jpg");
// 输出图像
header("Content-type: image/jpeg");
imagejpeg($image);
// 释放图像资源
imagedestroy($image);
?>
在上述示例中,我们首先使用imagecreatefromjpeg函数加载JPEG图像,然后使用header函数设置内容类型为JPEG,接着使用imagejpeg函数输出图像,并最终释放图像资源。
5. 处理本地图片
<?php
// 设置图片路径
$imagePath = "path/to/image.jpg";
// 输出图像
header("Content-type: image/jpeg");
readfile($imagePath);
// 注意:readfile函数会自动处理文件类型,无需再次设置Content-type
?>
6. 处理远程图片
<?php
// 设置远程图片URL
$imageUrl = "http://example.com/image.jpg";
// 获取图片内容
$imageData = file_get_contents($imageUrl);
// 输出图像
header("Content-type: image/jpeg");
echo $imageData;
// 注意:file_get_contents函数会自动处理文件类型,无需再次设置Content-type
?>