如何将Base 64图像存储到我的数据库和服务器文件夹。下面的代码是用来保存图像到我的服务器文件夹。但是图像打不开。
$data = $src;
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$file = '../emailtest'.rand() . '.png';
$success = file_put_contents($file, $data);
$data = base64_decode($data);
$source_img = imagecreatefromstring($data);
$rotated_img = imagerotate($source_img, 90, 0);
$file = '../emailtest'. rand(). '.png';
$imageSave = imagejpeg($rotated_img, $file, 10);
imagedestroy($source_img);
建议:1. 避免将二进制文件保存到数据库,尽可能将其保存到文件中。2. 宁愿将二进制文件保存到blob列,也不愿将base64保存到文本列。因为base64编码使它更大
在这里,我试着1. 从url下载图片2. 保存二进制文件到文件3.将二进制文件保存到db4. 将图像二进制转换为base645. 使用HTML <*img>标签显示base64图像
试试这段代码演示
<?php
$img_url = 'http://cdn-o7.outfit7.com/wp-content/uploads/2016/01/Icon-r-512-3.png';
$img_binary = file_get_contents($img_url);
$ext = pathinfo($img_url, PATHINFO_EXTENSION);
$img_base64 = "data:image/".$ext.";base64," . base64_encode($img_binary);
//save into file
$name = "emailtest_".rand().$ext;
file_put_contents($name, $img_binary);
echo "<img src='"$name'" title='"show from file'"/>";
//store to db
/* create your new table for testing
CREATE TABLE IF NOT EXISTS `table_img` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`img_binary` blob NOT NULL,
`location` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
*/
$insert="INSERT INTO table_img ('img_binary','location') VALUES('$img_binary','$name')"; //==>save to db using this query
$select="SELECT img_binary FROM table_img WHERE id=1"; //call your image binary using this query
// then convert binary into base64 with this : $img_base64= base64_encode(YOUR BINARY DATA FROM DATABASE);
//because i cant do it live in my server, i will shortcut call previous variable $img_base64 from above instead call binary from db and base64 encode
echo "<img src='"$img_base64'" title='"show from base64'"/>";
?>