2020.08.05
西安网络公司,HOOBOO在开发过程中,很多通过APP或者web前端会通过接口给我们以base64编码字符串的方式上传图片,这个时候我们就需要将这些base64编码字符串转化成图片,并且保存到本地,我们来讲解一下。
<?php
// 调用方法
public function uploads()
{
$content = $this -> getContent();
$this->base64_image_content($content, './uploads');
}
// base64编码字符串转换成图片并保存到本地
public function base64_image_content($base64_image_content, $path)
{
if( preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content,$result) )
{
$type = $result[2];
$new_file = $path . "/images/" . date('Ymd', time()) . "/";
if( !file_exists( $new_file ) )
{
// 检查是否有该文件夹,如果没有就创建,并给予最高权限
mkdir($new_file, 0700);
}
$new_file = $new_file.time().rand(1000,9999).".{$type}";
if ( file_put_contents( $new_file, base64_decode(str_replace($result[1], '', $base64_image_content))) )
{
return '/' . $new_file;
}else{
return false;
}
}else{
return false;
}
}
// 测试内容
public function getContent()
{
return $content ="data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAA6klEQVRYhe2WIQ7CQBBF
3xIUulmJbpAtJ2lSxQE4BJpDgCWoTXoSWF1d2aBri8CV2S4QYEX3yz8/mZfMZDIwdamxYltmCbAUSrU2thtkF0AqZBtt7M3VY
+4BLICD4OeAHXgpcBWyW+DoajDzAPxcwQGCy7eEBbATShttbD3IpsBZyO61sZWrh28JEyAT/IXDk7LJWIPgOxAcwDcCUX3PuS2zDkAbm7dldup71mp0o74IoNTTxVsJ3ksK
PoIIEAEiwKcAuTZWaWMVPI4RjyflbwBfUwSIABEgOIDvIamAi+DXDk86Rs27UNPSHT5bLdqHJYlmAAAAAElFTkSuQmCC";
}
?>