如何将Base 64映像存储到数据库和我的服务器文件夹

时间:2016-11-02 04:55:07

标签: javascript php html5-canvas

如何将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 个答案:

答案 0 :(得分:-1)

我的建议: 1.避免将二进制文件保存到数据库,如果可能,将其保存到文件中。 2.比将base64保存到文本列更喜欢将二进制文件保存到blob列中。因为base64编码使这个更大

这是,我试着 1.从网址下载图片 2.将二进制保存到文件中 3.将二进制文件保存到db 4.将图像二进制转换为base64 5.使用html< * img>显示图像base64标签

试试这段代码 DEMO

<?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\"/>";

?>