douyi3676 2013-03-16 17:34
浏览 66
已采纳

使用php和显示将图像存储到mysql DB中

Having big time problems in displaying an image out of my mysql database

I'm storing it in a longblob type

when the image is displayed i get a broken image icon

here is code for storing image

if(isset($_FILES['image']) && $_FILES['image']['size'] > 0 && isset($_POST['photoName']))
{
    //temporary file name
    // Temporary file name stored on the server
    $tmpName = $_FILES['image']['tmp_name'];
    $imageType = $_FILES['image']['type'];

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


    $sql="INSERT INTO photos (photoName, caption, photoData, photoType, userName)
        VALUES
        ('$_POST[photoName]','$_POST[caption]','$tmpName','$imageType', '$currentUser')";

    //For debugging purposes
    if(!mysqli_query($con,$sql))
    {
        die('Error: ' . mysqli_error($con));
    }
    else
    {
        echo "Your Image has been Added";
    }   
}

then printing the image

if(isset($_POST['usersImage'])){
        //code to show images
        $user = $_POST['usersImage'];
        $sql = "SELECT * FROM `photos` WHERE userName = '$user'";
        $result = mysqli_query($con,$sql);
        while($row = mysqli_fetch_array($result)) 
        {
            switch ($row['photoType']) {
                case 'image/jpeg':

                echo "<tr>";  
                echo '<img src="data:image/jpeg;base64,'. base64_encode($row['photoData'])."\"></td>";   
                echo "</tr>"; 
                    //echo '<img src="image>' .$row['photoData']. '.jpeg'.'</p>';
                    //echo '<p id="caption">'.$row['caption'].' </p>';
                break;
            }           
        }
    }

as you can see my latest attempt was to use base64 encoding to print out the image my previous try was the commented out code

  • 写回答

2条回答 默认 最新

  • duansao20000508 2013-03-16 17:41
    关注

    When you display the image it has to be from its own request. src="" should contain a url to a script that will deliver the content with the correct MIME header image/jpeg.

    <?php
        $photo_bin = //binary data from query here;
    
        header("Content-Type: image/jpeg"); // or whatever the correct content type is.
        echo $photo_bin;
    

    Quick example^ of a php script that can be requested by the browser from an img tag.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器