Home > Article > Backend Development > How can I display an image from binary data in a single script without saving it to disk?
Creating and Displaying Images from Binary Data within a Single Script
Many applications require the ability to process images from binary data and display them without intermediate storage on disk. This article explores how to achieve this functionality using data URIs.
Data URIs
Data URIs provide a way to embed binary data directly into HTML or CSS. They consist of three parts:
Using Data URIs for Images
To embed an image as a data URI, the following format is used:
data:[<MIME-type>][;charset="<encoding>"][;base64],<data>
For example, to embed a PNG image as a data URI using base64 encoding:
data:image/png;base64,<encoded-data>
Code Example
The following PHP function creates a data URI from a binary image file:
function data_uri($file, $mime) { $contents = file_get_contents($file); $base64 = base64_encode($contents); return ('data:' . $mime . ';base64,' . $base64); }
To display an image from binary data, you can simply use the data URI as the src attribute of an HTML element:
echo "<img src='" . data_uri('image.png', 'image/png') . "' alt='My Image' />";
Advantages of Data URIs
Using data URIs for images offers several advantages:
The above is the detailed content of How can I display an image from binary data in a single script without saving it to disk?. For more information, please follow other related articles on the PHP Chinese website!