PHP将图片转base64编码以及base64图片转换为图片并保存代码

太过爱你忘了你带给我的痛 2023-10-18 21:41 114阅读 0赞

一: 图片转base64编码

  1. /*图片转换为 base64格式编码*/
  2. $img = 'uploads/01.png';
  3. $base64_img = base64EncodeImage($img);
  4. echo '<img src="' . $base64_img . '" />';
  5. function base64EncodeImage ($image_file) {
  6. $base64_image = '';
  7. $image_info = getimagesize($image_file);
  8. $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
  9. $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
  10. return $base64_image;
  11. }

二:base64图片转换为图片并保存

  1. /* base64格式编码转换为图片并保存对应文件夹 */
  2. function base64_image_content($base64_image_content,$path){
  3. //匹配出图片的格式
  4. if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
  5. $type = $result[2];
  6. $new_file = $path."/".date('Ymd',time())."/";
  7. if(!file_exists($new_file)){
  8. //检查是否有该文件夹,如果没有就创建,并给予最高权限
  9. mkdir($new_file, 0700);
  10. }
  11. $new_file = $new_file.time().".{$type}";
  12. if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
  13. return '/'.$new_file;
  14. }else{
  15. return false;
  16. }
  17. }else{
  18. return false;
  19. }
  20. }
  21. echo base64_image_content($base64_img,"uploads/");

发表评论

表情:
评论列表 (有 0 条评论,114人围观)

还没有评论,来说两句吧...

相关阅读