如何将图像作为blob存储在数据库中?

时间:2012-10-30 21:54:05

标签: php mysql blobs

我正在尝试编写一个函数来处理mySQL / PHP中的图像,但无法确定如何存储结果。我已经包含了一个精简版的代码来演示这个问题。

image.image_o中的blob都已正确存储,可用于将图像输出到网页。该函数运行时没有错误,但之后image.image_r中的blob只有几个字节长,包含“资源ID#5”等文本

我确信我做的事情是愚蠢的 - 只是看不出它是什么。

function process_images(){
    global $mysql
    $sql = "select id, image_o from image";
    $res = mysqli_query($mysqli, $sql);
    if ($res){
        while ($ay = mysqli_fetch_array($res, MYSQLI_ASSOC)){
             $id = $ay['id'];
             $im = imagecreatefromstring($ay['image_o']);
             // do something useful with the image
             $sql2 = "update image set image_r = '{$im}' where id = $id";
             $res2 = mysqli_query($mysqli, $sql2);
             if ($res2){
                 // blah blah
             }else{
                 echo mysqli_error($mysqli)." in res2";
             }
         }
    }else{
        echo mysqli_error($mysqli)." in res"; 
    }
}

1 个答案:

答案 0 :(得分:0)

我同意上面的评论,这通常是不可取的。但是,这里有一篇很棒的文章,说明为什么你可能会这样做,以及如何做。它还强调了在数据库中存储图像的一些缺点。

http://forum.codecall.net/topic/40286-tutorial-storing-images-in-mysql-with-php/

您需要确保将数据读入字段。不只是文件指针:

// Temporary file name stored on the server
$tmpName  = $_FILES['image']['tmp_name'];  

// Read the file 
$fp     = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);

// Now take the contents of data and store THAT

简而言之,imagecreatefromstring返回“成功时将返回图像资源”,而不是文件本身的内容。您需要先读取该资源的内容,然后才能存储它。使用您的代码,进行以下更改:

function process_images(){
    global $mysql
    $sql = "select id, image_o from image";
    $res = mysqli_query($mysqli, $sql);
    if ($res){
        while ($ay = mysqli_fetch_array($res, MYSQLI_ASSOC)){
             $id = $ay['id'];
             $im = imagecreatefromstring($ay['image_o']);
             $tempFileName = '/tmp/' . $id . 'jpg';
             $imTempFile = imagegd($im, $tempFileName); 
             $fh = fopen($tempFileName, "r");
             $data = fread($fh, filesize($tempFileName));

             // do something useful with the image
             $sql2 = "update image set image_r = '{$data}' where id = $id";
             $res2 = mysqli_query($mysqli, $sql2);
             if ($res2){
                 // blah blah
             }else{
                 echo mysqli_error($mysqli)." in res2";
             }
             //delete the temp file
             unlink($tempFileName);
         }
    }else{
        echo mysqli_error($mysqli)." in res"; 
    }
}
相关问题