1、图片的base64编码
1 /*首先要确定图片的类型,需要安装一个php拓展php_fileinfo 2 如已安装可以在extension_dir目录下找到php_fileinfo.dll(windows),fileinfo.so(linux) 3 打开php.ini,把extension=php_fileinfo.dll前的";"去掉,然后重启apache。 4 */ 5 $file = 'tupian.png'; 6 $fi = new finfo(FILEINFO_MIME_TYPE); 7 $mime_type = $fi->file($file); //image/jpeg 8 //然后读取内容进行编码,拼接(建议用file_get_contents,因为是二进制,如果用fopen、fread就得模式要加b) 9 $base = 'data:'.$mime_type.';base64,'.base64_encode(bafile_get_contents($file)); //获得编码结果
2、base64图片解码
1 $base = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFEAAABRCAYAAACqj0o2AAAEdUlEQVR4Xu2cgbEMQRCG+0WACBABIkAEiAARIAJEgAgQASJABIgAESAC6qvaqTrr1k7P9j8zdzdTdeU9b7d35tvunp6enjuz0TYTONssYQiwATFACQbEATGAQICInjTxvJndMrOr04fh8TPt886//PzOzH4GjD9ERA8Q75rZPTO74RwRMF+Z2evWQFtCBN4TM7vkhDe//NskB5hNWguIQHuzY6pRA0cz7++YfpTcVTm1IWKyAMT/KRp+EpBvFcKXZNaEiN97WWlwgMRfVmm1IN6eNLDKoKaHVANZAyJhynuhCS+9GEz7Zg0fqYaI7/sUMAOXajAgL6tDIDVEQpjHpQSC7ns6hUBB4v4Vo4SIFn5tYMb7YKGNxJOSpoT43MweSHrtF0ogTnQgaUqIPzrRQsDhGy9ICJrJ8onMyEwoPbU7qiBcpYk9mXJ6kTKTVkH8YGbXe1LDaWJhgglvKog9+cNdaJLxSoSa2e/w1x0jUDJehVBSXcSHPTaWgbia0DYgBuBUQKRbw5wDXs6AGACxxxDnuyqbpDJnsspsRPXUDi7YbpHJXnthsky3ShPTov/c2sgq/p0EhGTDXwmxJ5OmYgLrkDQlxJ6C7oNNyvLWe9gekE0oSa2Vmsgz2CIgLd/KN/6aKi1kWwMMUg2RZ1D1wJZpiyZLxO4OpgZEnlez+iGN75GZkRyWt1oQGUjNbLfcD7bQxPTMGhopC6qXVLqmJqY+sInF2jp6smESIRYMzxeu+YMWENOs/dDM+GyFCTxcBR/JiqRXiKlfhECAxMwvrnV29neyMmgdsag0hFnrVytN3NcvzBxzJCQC7pXZRV8mTUu12qkYfm2M8r+3gsh2KqDS6YCIgaKNfD5GCPPIqAWRdTT5RbTMe0rAM550LVqKqRPqyDVWDRFw+LxIjfNCRTuZdGRHNVQQ8W3PVOl4L8XpemZuJqEXhfcv3hYNEbOluL2GyZayCD+qEQkR7QOg6nhFKbSl+3AzIVoZBbHGci4aIvLIvrNM3NQiIKJ9sirUTaPLu3kzyK0QD1UD53g3gdwCscdt0Tzd239V8SmDUojMwpQTH8okkgu3qGqsFCLp/p7DmFxo8+sIzK95s0ElEI/FDy6Bdpt1CUQKOLce9C7VlBr3uY+yeSEeuxaml+TSRi9EJpOWyYQamsgzXIeHPBB7POCjhJq9Z+2B2ENJiBLaXHb2tqsH4qmYcoJJuJN1eMgDsdc6bKV2EjOuZsZzIbasp1FCWpOdtYLJhXhs6+Q1eK5QJxfiqU0qA2KummVclxV0D038P8kBMUPT1i4JhcimDlugp9ZCIZ7aki8pS9bSL9cnIrTH83pKy6CmJyvx7IHIVgAg59VayoG0kk0FGgCz6h09EBkQIIkZe/nSoGjIFIyy88cYswDSAS/E1GlgkqBlJdPbt454wQIOC+OLK/lkw0sPKoU47ygTD2CTD2H7YGkLgf/3VsV6wFBBu1Q5m2oYk4/f/d3zjL+ujYJY3IFjuHFADHiLA+KAGEAgQMTQxACIfwBygLFS1arSnwAAAABJRU5ErkJggg=='; 2 $arr = preg_split("/(,|;)/",$base);//分隔三部分,data:image/png base64 后面一堆 3 $base64Data = $arr[2]; 4 $arr2 = explode('/',$arr[0]); //分割出图片格式 5 $type = $arr2[1]; 6 $fileName = 'tupian.'.$type; //拼接图片名称 7 file_get_contents($fileName,base64_decode($base64Data));