Home >Backend Development >PHP Tutorial >Can Images Be Displayed Directly from Binary Data Using Data URIs?
Creating and Displaying Images from Binary Data
Can you create and display images from binary data directly in a single script? This question stems from a desire to handle image processing and display without relying on external scripts or writing images to disk.
The answer lies in using data URIs. Data URIs follow a specific format:
data:[<MIME-type>][;charset="<encoding>"][;base64],<data>
MIME types specify the format of the data, such as image/png or image/jpeg. The charset and base64 are optional. The actual data is represented in base64 encoding.
To generate a data URI from binary data, you can use a function like the following:
function data_uri($file, $mime) { $contents = file_get_contents($file); $base64 = base64_encode($contents); return ('data:' . $mime . ';base64,' . $base64); }
With this function, you can then use the data URI as the src attribute of an image:
<img src="<?php echo data_uri('elephant.png','image/png'); ?>" alt="An elephant" />
The above is the detailed content of Can Images Be Displayed Directly from Binary Data Using Data URIs?. For more information, please follow other related articles on the PHP Chinese website!