Home > Article > Backend Development > How Can I Display Images from Binary Data in PHP Using Data URIs?
Recreating and Displaying Images from Binary Data in PHP
In PHP, it's possible to process and display an image directly from its binary data, eliminating the need to store it to disk or use external scripts. This can be achieved using data URIs in the image's source attribute.
Data URI Format
A data URI consists of the following parts:
data:[<MIME-type>][;charset="<encoding>"][;base64],<data>
Example:
Consider the following code, which displays an image from its binary data:
function data_uri($file, $mime) { $contents = file_get_contents($file); $base64 = base64_encode($contents); return ('data:' . $mime . ';base64,' . $base64); } echo "<img src='" . data_uri('elephant.png', 'image/png') . "' alt='An elephant' />";
Usage
This code sample demonstrates how to use data URIs to display an image:
// Get the binary data of image 1 $imageData1 = file_get_contents('assets/test.png'); // Process the image data (if needed) // ... // Convert the image data to a data URI $dataURI1 = 'data:image/png;base64,'.base64_encode($imageData1); // Display image 1 using the data URI echo "<img src='$dataURI1' />"; // Repeat for image 2, and so on...
By utilizing data URIs, you can efficiently recreate and display images from binary data, streamlining your workflow and optimizing performance.
The above is the detailed content of How Can I Display Images from Binary Data in PHP Using Data URIs?. For more information, please follow other related articles on the PHP Chinese website!