Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP: recreate and display an image from binary data
In PHP, you can recreate and display an image from binary data using data URIs. This technique embeds image data directly into HTML without requiring external image files.
Data URI Format
Data URIs follow this format −
data:[<MIME-type>][;charset=<encoding>][;base64],<data>
Creating a Data URI Function
Here's a PHP function that converts an image file to a data URI ?
<?php
function data_uri($file, $mime) {
$contents = file_get_contents($file);
$base64 = base64_encode($contents);
return ('data:' . $mime . ';base64,' . $base64);
}
?>
Displaying Image from Binary Data
You can display the image directly in HTML using the data URI ?
<img src="<?php echo data_uri('some_image.png', 'image/png'); ?>" alt="Image sample" />
Complete Example
Here's a working example that creates binary data and displays it as an image ?
<?php
function create_image_from_binary($binary_data, $mime_type) {
$base64 = base64_encode($binary_data);
return 'data:' . $mime_type . ';base64,' . $base64;
}
// Example: Create a simple PNG binary data (1x1 transparent pixel)
$binary_data = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==');
// Recreate and display the image
$data_uri = create_image_from_binary($binary_data, 'image/png');
?>
<!DOCTYPE html>
<html>
<head>
<title>Image from Binary Data</title>
</head>
<body>
<h2>Image recreated from binary data:</h2>
<img src="<?php echo $data_uri; ?>" alt="Recreated Image" style="width:100px; height:100px; border:1px solid #ccc;" />
</body>
</html>
Key Points
The data_uri() function reads file contents, encodes them in base64, and returns a complete data URI. This approach allows you to display images without storing them to disk after processing, making it useful for dynamically generated or temporary images.
Conclusion
Data URIs provide a convenient way to embed binary image data directly into HTML. This technique is particularly useful for avoiding file system storage and displaying processed images immediately.
