Home
Linux
Golang
MySQL
PHP
Other
PHP将网络图片转base64
创建日期:2019-09-02 16:53:20
更新日期:2023-09-26 10:33:55
栏目:
PHP
浏览:1242
html2canvas图片会跨域的问题,试了好多方法不行,还是转base64最靠谱。 解决方法有两种,一种是将网络图片保存在服务器,转base64后删除,一种是直接将网络上的图片转base64。 ## 一、将图片保存在服务器,然后转base64 ``` //将网络图片保存在本地 public function InternetImgSave($url) { $state = @file_get_contents($url, true);//获取网络资源的字符内容 if ($state) { $filename = time() . mt_rand(100, 999) . strrchr($url, '.'); ob_start();//打开输出 readfile($url);//输出图片文件 $img = ob_get_contents();//得到浏览器输出 ob_end_clean();//清除输出并关闭 $fp2 = @fopen($filename, "a"); fwrite($fp2, $img);//向当前目录写入图片文件,并重新命名 fclose($fp2); $img = $this->base64EncodeImage($filename);//转成base64 unlink($filename);//删除图片 return $img; } else { return false; } } //转base64 private function base64EncodeImage($image_file) { $base64_image = ''; $image_info = getimagesize($image_file); $image_data = fread(fopen($image_file, 'r'), filesize($image_file)); $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data)); return $base64_image; } ``` ## 二、直接转base64 ``` public function base64EncodeImage($url) { $state = @file_get_contents($url, true);//获取网络资源的字符内容 if ($state) { ob_start();//打开输出 readfile($url);//输出图片文件 $img = ob_get_contents();//得到浏览器输出 ob_end_clean();//清除输出并关闭 $base64_image = 'data:image/png;base64,' . chunk_split(base64_encode($img)); return $base64_image; } else { return false; } } ```
内容版权声明:本文为舒孝元原创文章,转载无需和我联系,但请注明来自
舒孝元博客:https://www.shuxiaoyuan.com/info/18
联系邮箱:sxy@shuxiaoyuan.com