Home >Backend Development >PHP Tutorial >How to Display Recreated Images from Binary Data Directly in PHP?

How to Display Recreated Images from Binary Data Directly in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-09 13:56:02285browse

How to Display Recreated Images from Binary Data Directly in PHP?

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:

  • MIME-type: Specifies the type of data being embedded, such as "image/png" or "image/jpeg".
  • charset: Optional parameter specifying the character encoding of the data, typically "base64".
  • data: The binary data encoded as base64.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn