【问题标题】:How to Store Base 64 Image into Database, and to My Server Folder如何将 Base 64 图像存储到数据库和我的服务器文件夹中
【发布时间】:2017-03-15 08:09:06
【问题描述】:

如何将 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);

【问题讨论】:

  • 我想将 Base64 图像保存到我的服务器文件夹,并且需要将路径保存到我的数据库。

标签: javascript php html5-canvas


【解决方案1】:

我的建议: 1.避免将二进制文件保存到数据库中,尽可能将其保存到文件中。 2. 将二进制保存到 blob 列优于将 base64 保存到 text 列。因为base64编码让这个更大

在这里,我尝试 1.从url下载图片 2. 将二进制存入文件 3. 保存二进制到数据库 4. 将图片二进制转base64 5.使用html 标签

显示图片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\"/>";

?>

【讨论】:

  • 我需要将图像保存到服务器文件夹中
  • file_get_contents 然后是 file_put_contents。或者你可以使用 ftp_put。搜索php ftp
  • 如果你想要完整的答案。请编辑您的问题。我用简单的答案来回答你的问题,因为你写的问题很简单
猜你喜欢
  • 2019-08-29
  • 2013-06-13
  • 2019-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
相关资源
最近更新 更多