【问题标题】:using <img> tag to call PHP script for displaying encoded image retrieved from database使用 <img> 标签调用 PHP 脚本以显示从数据库检索到的编码图像
【发布时间】:2018-04-28 17:37:10
【问题描述】:

我的 PHP 脚本,用于将编码的图像数据作为“blob”类型存储在数据库表中:

include './libraries/LIB_mysql.php'; # library for using the 'insert()' function at the end
$imageFilePath = "./pythonProgrammingProgram.PNG";
$imageFileRead = file_get_contents($imageFilePath); # == �PNG  IHDR�A ... uY�IEND�B`� (... and so on)
$imageEncode = base64_encode($imageFileRead); # iVBORw0KGgoAAAA (... and so on)
$data_array['image_id'] = 3;
$data_array['image_file'] = $imageEncode;
$table = 'images';
insert(DATABASE, $table, $data_array);

图像数据似乎已正确存储在数据库中:

mysql> select * from images;
| image_id | image_file
|        3 | iVBORw0KGgoAAAA # (... and so on)

然后我想使用“img”标签在 HTML 页面中显示图像,该标签调用 PHP 脚本:&lt;img src="./imageDisplay.php?pictureID=3"&gt;。 PHP脚本imageDisplay.php从数据库中检索图像数据并回显解码后的图像:

header("Content-type: image/png");
include('./libraries/LIB_mysql.php'); # for using exe_sql() function
$image_id = $_GET['pictureID']; # == 3 -> corresponds to the value in the database !!
$sql = "SELECT image_file FROM images WHERE image_id = '" . $image_id . "'"; # $image_id";
list($img) = exe_sql(DATABASE, $sql); # $img contains the decoded data: == �PNG  IHDR�A ... uY�IEND�B`� (... and so on)
echo base64_decode($img);
exit;

在本地主机上加载 HTML 文件时,我看到损坏的图像。在 Firefox 下的 Network -> Response 我看到:

Name: imageDisplay.php
Dimensions: 0 × 0
MIME Type: image/png

我猜图像数据的传输不起作用,但我真的不明白为什么。 base64_decode($img)中的解码图像数据与编码前$imageFileRead中的相同,所以我猜数据库操作不是问题,而是echo base64_decode($img);&lt;img src="./imageDisplay.php?pictureID=3"&gt;的某个地方。找到了这个(SO question)[PHP - call a function from a img src和(this other)[The image cannot be displayed because it contains errors,但仍然看不到如何解决它:-(

【问题讨论】:

    标签: php html image


    【解决方案1】:

    我会认真重新考虑将图像存储在数据库中。最好的方法是保存文件并将图像路径保存在数据库中。如果这是绝对必需的,请尝试使用此代码保存:

    $name = $_FILES['file']['name'];
    $target_dir = "upload/";
    $target_file = $target_dir . basename($_FILES["file"]["name"]);
    
    // Select file type
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
    
    // Valid file extensions
    $extensions_arr = array("jpg","jpeg","png","gif");
    
    // Check extension
    if( in_array($imageFileType,$extensions_arr) ){
    
    // Insert record
    $query = "insert into images(name) values('".$name."')";
    mysqli_query($con,$query);
    
    // Upload file
    move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
    

    这个代码要显示

    $sql = "select name from images where id=1";
    $result = mysqli_query($con,$sql);
    $row = mysqli_fetch_array($result);
    
    $image = $row['name'];
    $image_src = "upload/".$image;
    
    ?>
    <img src='<?php echo $image_src;  ?>' >
    

    此代码来自此示例 - http://makitweb.com/upload-and-store-an-image-in-the-database-with-php/#base64

    您需要修改它以使用您的代码。

    【讨论】:

    • 我在上面发布的代码与教科书中的代码非常相似,这就是为什么我更感兴趣的是它应该如何体面地工作,而不是替代品。但当然感谢您的建议和代码建议。只是它来自教科书,教科书网站上没有关于它的勘误表,所以我想它应该可以工作,但我不知道为什么我不能让它工作?几乎是 1:1
    • 您是否尝试过仅显示 BLOB?使用相同的代码但不使用 base64_decode() 并查看是否允许显示。
    【解决方案2】:
    <form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file" accept="png/jpeg/jpg/image"><br><br>
    <input type="submit" value="submit" name="submit">
    </form>
    <?php 
     if(isset($_POST['submit'])){`enter code here`
        $name       = $_FILES['file']['name'];  `enter code here`
        $temp_name  = $_FILES['file']['tmp_name'];  
         // $allowed = array("pdf" => "pdf");
         // var_dump($name,$temp_name);
        if(isset($name)){
            if(!empty($name)){      
                $location = './uploads1/';      
                if(move_uploaded_file($temp_name, $location.$name)){
                //var_dump($temp_name,$location.$name);
                    echo 'File uploaded successfully';
    
                    $con=mysqli_connect("localhost","root","");
    echo "connect";
    if(!$con)
    {
    die("not connect");
    }
    mysqli_select_db($con,"dstpurse"); 
    
    
    $query="INSERT INTO `image_upload`(`name`,`path`) VALUES('$name','$location')";
    
    $result=mysqli_query($con,$query);
    if($result)
    {
    echo "inserted";
    }
    else
    {
    echo "not inserted";
    }
    
                }
            }       
        }  else {
            echo 'You should select a file to upload !!';
        }
        $query1 = "SELECT * FROM `image_upload`";
    $result1 = mysqli_query($con,$query1) or die("query failed:".mysqli_error());
    while($row=mysqli_fetch_array($result1))
    {
    var_dump($name); 
    
    echo "<a href=".$location.$name.">dowenload</a>";
    
    }
    
    
    }
    
    ?>
    

    【讨论】:

    • 我不寻找替代代码来获取保存在数据库中然后显示的图像,而是寻找阻止它与发布的代码一起显示的错误。它遵循的方案是: 1. 使用file_get_contents() 获取图像内容; 2. 使用 base64_encode() 编码; 3. 插入数据库; 4. 加载带有 标签的 HTML,其src 属性调用 PHP 脚本并在其 URL 查询字符串中提供图像选择标准; 5. PHP脚本从数据库中检索编码后的图片内容,解码,然后通过在header中定义为image/png来回显图片内容。
    【解决方案3】:
    <form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file" accept="png/jpeg/jpg/image"><br><br>
    <input type="submit" value="submit" name="submit">
    </form>
    <?php 
     if(isset($_POST['submit'])){`enter code here`
        $name       = $_FILES['file']['name'];  `enter code here`
        $temp_name  = $_FILES['file']['tmp_name'];  
         // $allowed = array("pdf" => "pdf");
         // var_dump($name,$temp_name);
        if(isset($name)){
            if(!empty($name)){      
                $location = './uploads1/';      
                if(move_uploaded_file($temp_name, $location.$name)){
                //var_dump($temp_name,$location.$name);
                    echo 'File uploaded successfully';
    
                    $con=mysqli_connect("localhost","root","");
    echo "connect";
    if(!$con)
    {
    die("not connect");
    }
    mysqli_select_db($con,"dstpurse"); 
    
    
    $query="INSERT INTO `image_upload`(`name`,`path`) VALUES('$name','$location')";
    
    $result=mysqli_query($con,$query);
    if($result)
    {
    echo "inserted";
    }
    else
    {
    echo "not inserted";
    }
    
                }
            }       
        }  else {
            echo 'You should select a file to upload !!';
        }
        $query1 = "SELECT * FROM `image_upload`";
    $result1 = mysqli_query($con,$query1) or die("query failed:".mysqli_error());
    while($row=mysqli_fetch_array($result1))
    {
    var_dump($name); 
    
    echo "<a href=".$location.$name.">dowenload</a>";
    
    }
    
    
    }
    
    ?>
    

    【讨论】:

    • 请在您的答案中添加解释和一些 cmets。事实上,它不会很有帮助。另外,你有一些//ed 一些行——为什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2013-01-13
    相关资源
    最近更新 更多