Can Images Be Displayed Directly from Binary Data Using Data URIs?

Barbara Streisand
Release: 2024-11-07 05:56:02
Original
361 people have browsed it

Can Images Be Displayed Directly from Binary Data Using Data URIs?

Creating and Displaying Images from Binary Data

Can you create and display images from binary data directly in a single script? This question stems from a desire to handle image processing and display without relying on external scripts or writing images to disk.

The answer lies in using data URIs. Data URIs follow a specific format:

data:[<MIME-type>][;charset="<encoding>"][;base64],<data>
Copy after login

MIME types specify the format of the data, such as image/png or image/jpeg. The charset and base64 are optional. The actual data is represented in base64 encoding.

To generate a data URI from binary data, you can use a function like the following:

function data_uri($file, $mime) 
{  
  $contents = file_get_contents($file);
  $base64   = base64_encode($contents); 
  return ('data:' . $mime . ';base64,' . $base64);
}
Copy after login

With this function, you can then use the data URI as the src attribute of an image:

<img src="<?php echo data_uri('elephant.png','image/png'); ?>" alt="An elephant" />
Copy after login

The above is the detailed content of Can Images Be Displayed Directly from Binary Data Using Data URIs?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!