DeTechn Blog

php 读取base64到网页显示并存到新文件

<?php

function bs64toimg($btxt,$path){
//匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $btxt, $result)){
 $type = $result[2];
 $new_file = $path;
 if(!file_exists($new_file)){
 mkdir($new_file, 0700);
 }
 $new_file .= date('Ymdhis').".{$type}";
 if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $btxt)))){
 return '/'.$new_file;
 }else{
 return false;
 }
 }else{
 return false;
 }
}

function imgtobs64($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;
}

$img = 'imgstotxt.jpg';
$base64_img = imgtobs64($img);//读取图片(imgfiles to base64)
echo bs64toimg($base64_img,"uploads/");//写入图片(base64 to imgfiles)

?>

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »