0

mySQL / PHP で画像を処理する関数を作成しようとしていますが、結果を保存する方法がわかりません。問題を示すために、コードの簡略化されたバージョンを含めました。

image.image_o のブロブはすべて正しく保存され、Web ページに画像を出力するために使用できます。関数はエラーなしで実行されますが、その後、image.image_r のブロブの長さはほんの数バイトで、「Resource 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"; 
    }
}
4

1 に答える 1

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"; 
    }
}
于 2012-10-30T22:15:37.650 に答える