Repository navigation
Expand file tree
/
Copy pathImageTools.php
More file actions
70 lines (55 loc) · 1.8 KB
/
Copy pathImageTools.php
File metadata and controls
70 lines (55 loc) · 1.8 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
header('content-type:text/html;charset=utf-8');
/**
* Class ImageTools
* 图片工具类
*/
class ImageTools{
/**
* @desc Base64生成图片文件,自动解析格式
* @param $base64 可以转成图片的base64字符串
* @param $path 绝对路径
* @param $filename 生成的文件名
* @return array 返回的数据,当返回status==1时,代表base64生成图片成功,其他则表示失败
*/
public function base64ToImage($base64, $path, $filename) {
$res = array();
//匹配base64字符串格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)) {
//保存最终的图片格式
$postfix = $result[2];
$base64 = base64_decode(substr(strstr($base64, ','), 1));
$filename .= '.' . $postfix;
$path .= $filename;
//创建图片
if (file_put_contents($path, $base64)) {
$res['status'] = 1;
$res['filename'] = $filename;
} else {
$res['status'] = 2;
$res['err'] = 'Create img failed!';
}
} else {
$res['status'] = 2;
$res['err'] = 'Not base64 char!';
}
return $res;
}
/**
* @desc 将图片转成base64字符串
* @param string $filename 图片地址
* @return string
*/
public function imageToBase64($filename = ''){
$base64 = '';
if(file_exists($filename)){
if($fp = fopen($filename,"rb", 0))
{
$img = fread($fp,filesize($filename));
fclose($fp);
$base64 = 'data:image/jpg/png/gif;base64,'.chunk_split(base64_encode($img));
}
}
return $base64;
}
}