PHP把无Content-type的文件打印为图像

First Post:

Last Update:

Word Count:
176

Read Time:
1 min

用了GD库,记得开扩展

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* @param string url 图片地址
* @param string type 图片类型
*/

$url = '';
$type = '';

switch ($type) {
case 'png':
header("Content-type: image/png");
$im = imagecreatefrompng($url);
imagepng($im);
imagedestroy($im);
break;
case 'jpeg':
header("Content-type: image/jpeg");
$im = imagecreatefromjpeg($url);
imagejpeg($im);
imagedestroy($im);
break;
case 'webp':
header("Content-type: image/webp");
$im = imagecreatefromwebp($url);
imagewebp($im);
imagedestroy($im);
break;
case 'gif':
header('Content-type: image/gif');
$im = imagecreatefromgif($url);
imagegif($im);
imagedestroy($im);
break;
case 'wbmp':
header('Content-type: image/wbmp');
$im = imagecreatefromwbmp($url);
imagewebp($im);
imagedestroy($im);
break;
case 'svg':
header('Content-type: image/svg+xml');
echo file_get_contents($url);
break;
default:
http_response_code (503);
echo json_encode(
array(
"code" => 503,
"message" => 'No set \'type\' or \'type\' can\'t identify'
)
);
break;
}