在 php 脚本中显示图像
我有一些名称中没有扩展名的图像。现在,当我想打开它们时,某些浏览器无法将数据检测为图像并显示二进制文本。
什么是正确的脚本(php),它将获取此类图像的地址,检测其格式并使用图像输出设置正确的标题?
I have some images without extension in their name. Now, when I want to open them some browsers can't detect data as image and show up the binary text.
What is the right script (php) which will take the address of such image, detect it's format and set right headers with image output?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 exif_imagetype 函数来正确检测什么类型它是图像,然后 image_type_to_mime_type 函数来获取您想要的 mime 类型:
不过您需要内置的 exif 支持。我推荐这样做,因为它实际上检查文件的签名,而不是盲目地根据扩展名假设 mime 类型。但是,如果这不是一个选项,您将不得不回退到 fileinfo 正如其他人提到的。
You can use the exif_imagetype function to properly detect what type of image it is, then the image_type_to_mime_type function to get the mime type you want:
You'll need exif support builtin though. I recommend this because it actually checks the signature of the file versus blindly assuming the mime type based on extension. However, if this isn't an option, you'll have to fallback to fileinfo as others have mentioned.
你应该检查 fileinfo()
http://www.php.net/manual/en/function.finfo -文件.php
Fileinfo 检测文件类型,并根据该类型您可以设置标头。
You should check fileinfo()
http://www.php.net/manual/en/function.finfo-file.php
Fileinfo detects the filetype and depending on that u can set your header.
你可以使用这个:
图像是一个 gif";
休息;
案例“IMAGETYPE_JPEG”:
echo "图像是 jpeg";
休息;
案例“IMAGETYPE_PNG”:
echo "图像是一个 png";
休息;
}
?>
You could use this :
<?php
$filename = 'http://static.php.net/www.php.net/images/php.gif';
$file = fopen($filename, 'rb');
$size = getimagesize($file);
switch ($size['mime']) {
case "IMAGETYPE_GIF":
echo "<strong class="highlight">Image</strong> is a gif";
break;
case "IMAGETYPE_JPEG":
echo "<strong class="highlight">Image</strong> is a jpeg";
break;
case "IMAGETYPE_PNG":
echo "<strong class="highlight">Image</strong> is a png";
break;
}
?>
您可以使用
finfo_file()
确定相关文件的 MIME 类型,然后发送包含该信息的 Content-Type 标头。You could use
finfo_file()
to determine the MIME type of the file in question and then send a Content-Type header with that information in.