【问题标题】:rotate image from database and save to database blob type从数据库中旋转图像并保存到数据库 blob 类型
【发布时间】:2015-12-10 02:23:16
【问题描述】:

保存图片到数据库

$query =$myClass->query("insert into tblImage(document) values(".base64_encode(file_get_contents($_FILES['imageFile']["tmp_name"])).")");   

显示数据库中的图像

$image =$myClass->query("select document from  tblImage where code=1");                                                                             
$output_bin_string = base64_decode($image[0]['thumbDocument']);
header("Content-Type: image/jpeg");
header("Content-Length: " . strlen($output_bin_string));          
echo $output_bin_string;    

我可以将图像保存到文件,然后保存到数据库

$image=$myClass->query('select document form tblImage where code=1' );   
$source = imagecreatefromstring(base64_decode($image[0]["document"])) ;
$rotate = imagerotate($source,$degrees,0);
imagejpeg($rotate,'tmp/1.jpg');
$image =$myClass->query("update tblImage set document='".base64_encode(file_get_contents('tmp/1.jpg'))."'   where code=1");

问题:有一种方法可以旋转图像并保存到数据库,而无需像这样将图像保存到文件中

$image=$myClass->query('select document form tblImage where code=1' );   
$source = imagecreatefromstring(base64_decode($image[0]["document"])) ;
$rotate = imagerotate($source,$degrees,0);
$image =$myClass->query("update tblImage set document='".base64_encode($rotate)."'   where code=1");

这段代码说错误:base64_encode() expects parameter 1 to be string, resource given

【问题讨论】:

    标签: php database image


    【解决方案1】:

    将文件保存在数据库中是一种不好的做法,与本机文件系统访问或其他存储后端(如 S3)相比,性能非常差。看看这个问题:Saving images in database mysql

    您的方法将导致数据在到达客户端之前通过数据库、php 和网络服务器。将其直接保存在文件系统中并在数据库中保留对文件的引用将允许您在请求时直接通过网络服务器发送它。

    一个正确的方法是拥有一个表,例如,在保存对文件的引用的应用程序中,我们称之为file_storage。然后根据需要关联行:例如用户 1:1 头像、用户 1:n 照片、照片 n:n 画廊。这是 DRY,维护 SoC,甚至允许我将文件存储在不同的后端。您还可以阅读this plugin for CakePHP 的文档,它完全符合我刚才的描述。

    对于图像处理,我建议使用Imagine 库。以下是从文档中获取的示例:

    use Imagine\Image\Box;
    use Imagine\Image\Point;
    
    $image->resize(new Box(15, 25))
       ->rotate(45)
       ->crop(new Point(0, 0), new Box(45, 45))
       ->save('/path/to/new/image.jpg');
    

    【讨论】:

      【解决方案2】:

      您应该首先将图像资源转换为字符串(通过将输出缓冲到变量中),然后将其保存到数据库中,如下所示:

      // ... your previous code
      $rotate = imagerotate($source,$degrees,0);
      // New code starts here
      ob_start();
      imagejpeg($rotate);
      $imageData = ob_get_clean(); 
      $image =$myClass->query("update tblImage set document='".base64_encode($imageData)."'   where code=1");
      

      请注意,这必须在向客户端发送任何输出之前完成,否则 ob_start() 将失败。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        • 2020-09-03
        • 2023-03-15
        • 1970-01-01
        • 2011-02-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多