php: recreate and display an image from binary data

2022-08-30 13:17:42

Is it possible to recreate images from binary data (process them if needed) and display them, all in the same script? Something like

// get and display image 1:
$imagedata1 = file_get_contents('assets/test.png');
$imagedata1 = process_using_gd_or_something($imagedata1);

echo "<img src={$imagedata1} >"; // <-- IS THIS (OR EQUIVALENT) POSSIBLE?

// get and display image 2:
//etc...

I want to avoid storing the images to to disk after processing and getting them from there, or using an external script...


答案 1

You can do this using a data URI in the image attribute.src

The format is: data:[<MIME-type>][;charset="<encoding>"][;base64],<data>

This example is straight from the Wikipedia page on data URIs:

<?php
function data_uri($file, $mime) 
{  
  $contents = file_get_contents($file);
  $base64   = base64_encode($contents); 
  return ('data:' . $mime . ';base64,' . $base64);
}
?>

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

答案 2

This is actually possible using inline images (called data URIs).

Your image tag would look something like this:

<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/
/ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp
V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7" 
width="16" height="14" alt="embedded folder icon">

Why they are mostly not a good idea:

  • Page load will be slowed down because the image needs to be fetched before the full HTML structure can be loaded and thus, rendered. Even more so if you are performing additional operations on the image. Your site will very likely feel much slower than if it were an external image.

  • Inline images need to be base64 encoded, adding 33% to their size.

If you are talking about a reasonable high-traffic, public site, I would recommend you store your image externally, and cache them. If it's just for a small project, inline images may work for you.


推荐