Displaying Recreated Images from Binary Data in PHP
A common task involves retrieving and displaying images stored as binary data. To optimize this process, it's desirable to both process and display the images within the same script without the need for external storage or scripts.
Solution:
PHP provides a solution through the use of data URIs. These URIs embed binary data directly into HTML, allowing them to be displayed without referencing an external file.
The syntax for data URIs is as follows:
data:[<MIME-type>][;charset="<encoding>"][;base64],<data>
Where:
To process the binary data, use an appropriate PHP function such as gd_imagecreatefromstring() to load the image from the binary stream. Once processed, convert the image back to binary using imagepng() or imagejpeg().
Finally, encode the data as base64 using base64_encode(). This encoded data can then be used as the source for the HTML image tag:
<?php function data_uri($binary_data, $mime_type) { return 'data:' . $mime_type . ';base64,' . base64_encode($binary_data); } // Get binary data of image $imagedata = get_binary_data(); // Process image $processed_imagedata = process_image($binary_data); // Display image using data URI echo '<img src="' . data_uri($processed_imagedata, 'image/png') . '" alt="Processed Image">'; ?>
The above is the detailed content of How to Display Recreated Images from Binary Data Directly in PHP?. For more information, please follow other related articles on the PHP Chinese website!