How to read images from MySQL database using PHP?

后端 未结 2 1549
半阙折子戏
半阙折子戏 2020-12-12 05:19

How to read images from MySQL database using PHP?

If the images are stored in a BLOB in the database, how to use the binary data that I get and turn it into an image

相关标签:
2条回答
  • 2020-12-12 05:49

    What you should probably do, if storing images as BLOBs, is provide a URL that calls your script in a way that it can determine what image to return.

    Use that URL as the src, or background-image: url(...) and in the script, read the BLOB from the database in to a variable.

    Then output the variable after appropriate header information, telling the browser it is to receive an image, for instance:

    header('Content-Type: image/jpeg');
    

    Sending a Content-Length header and sensible information on caching/expiry would also be wise.


    NB. Having said all that, I tend to be wary of using BLOBs in databases, they tend to cripple performance. When I want to store images, I store then in some directory structure and reference them in the database in some fashion.

    0 讨论(0)
  • 2020-12-12 06:00

    To directly use the binary data as a an image source, you can use the data URI scheme, for example:

    $uri = 'data:image/png;base64,'.base64_encode($row['binary-data']);
    

    This URI can then be used directly as the image’s source:

    background-image: url(<?php echo $uri; ?>)
    <img src="<?php echo $uri; ?>">
    

    But that has some substantial disadvantages: Besides the lack of support for these data URIs in older browsers, data URIs do also have disadvantaged regarding payload, caching, and references.

    0 讨论(0)
提交回复
热议问题