php 设置标题( content-type: image/<ANY IMG FORMAT>)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23820011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:59:02  来源:igfitidea点击:

Set the header( content-type: image/<ANY IMG FORMAT>)

phphttp-headerssubstr

提问by user3663049

The php file that handles the images I display only allows one image format, either .jpg, .png, .bmp, etc but not all. The imageName stores the file name of the image stored in the database including its format. this is my code, so far it doesn't work yet and I'm not sure if that's allowed. Can you help me fix it please?

处理我显示的图像的 php 文件只允许一种图像格式,.jpg、.png、.bmp 等,但不是全部。imageName 存储数据库中存储的图像的文件名,包括其格式。这是我的代码,到目前为止它还不起作用,我不确定这是否允许。你能帮我修一下吗?

$con = mysqli_connect("localhost","root","","tickets");
$ticket = 109;
$result = mysqli_query($con,"SELECT image, imageName FROM tix WHERE tktNum=$ticket");


while($row = mysqli_fetch_array($result))
{
    $image = $row['image'];
    $imageName = $row['imageName'];
    $format = substr( $imageName, -3 ); //gets the last 3 chars of the file name, ex: "photo1.png" gets the ".png" part
    header('content-type: image/' . $format);
}

回答by John

I just used this, just indicating it's an image but without specifying image type.

我只是用了这个,只是表明它是一个图像,但没有指定图像类型。

header("Content-type: image");

It seems to be working just fine regardless of file type. I tested with IE, Firefox, Safari and the Android browser.

无论文件类型如何,它似乎都可以正常工作。我用 IE、Firefox、Safari 和 Android 浏览器进行了测试。

回答by D555

The solution is to read in the file and decide which kind of image it is and basednd on it send out the appropriate header.

解决方案是读入文件并决定它是哪种图像并基于它发送适当的标题。

$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename,"."),1));

switch( $file_extension ) {
    case "gif": $ctype="image/gif"; break;
    case "png": $ctype="image/png"; break;
    case "jpeg":
    case "jpg": $ctype="image/jpeg"; break;
    case "svg": $ctype="image/svg+xml"; break;
    default:
}

header('Content-type: ' . $ctype);