How to store php imagejpg() result in mysql database

时间:2017-08-05 12:20:27

标签: php image-processing mysqli php-gd

I have resized the image that I received from the user using the below code:

$imagedata = getimagesize($_FILES['uploadedimage']['tmp_name']);
            $newwidth = $imagedata['0']/3;
            $newheight = $imagedata['1']/3; 
            $thumb = imagecreatetruecolor($newwidth, $newheight);
            $source = imagecreatefromjpeg($_FILES['uploadedimage']['tmp_name']);
            // Resize
            imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $imagedata['0'], $imagedata['1']);

            // Output and free memory
            ob_start();
            imagejpeg( $thumb );
            echo '<img src="data:image/jpeg;base64,' . base64_encode(ob_get_clean()) . '">';
            imagedestroy($thumb);

now I am using this line

echo '<img src="data:image/jpeg;base64,' . base64_encode(ob_get_clean()) . '">';

to display the image but instead, I want to store it in my database. I am not able to figure it out. I have searched in many forums and have failed to find any answer. Please help.

3 个答案:

答案 0 :(得分:1)

您不应该存储图像,您可以做的是将图像存储在已知路径中,然后将唯一ID或名称存储在db中,然后检索您在db中查找id并构造路径。

Is it a good practice to save a base64 string on the Database?

答案 1 :(得分:0)

我通过添加写入echo的代码行来解决这个问题:

$image = addslashes(ob_get_contents());

现在可以使用查询将$ image正常发送到DB。

答案 2 :(得分:0)

除非你真的必须这样做,否则你不会存储blob。

你宁愿每天备份......

  • 100MB数据库和50GB文件(差异化,使用rsync)
  • 或50GB的SQL数据库?