How to Embed Images in a Single HTML/PHP File

How to embed images in a single HTML / PHP file?

A solution to embed an image directly in an HTML page would be to use the data URI scheme

For instance, you could use some portion of HTML that looks like this :

<img src="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP
C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA
AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J
REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq
ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0
vr4MkhoXe0rZigAAAABJRU5ErkJggg==" alt="Red dot" />

There are other solutions on the wikipedia page I linked to :

  • including the image as a CSS rule
  • Using some Javascript.

But note those solutions will not work on all browsers -- up to you to decide whether this is acceptable or not, in your specific situation.


Edit : to answer the question you asked about "how to generate Data URL's properly with PHP", take a look a bit lower in the wikipedia page about the Data URI scheme, which gives this portion of code (quoting) :

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" />

Include html file with image using PHP

The logic of including a file into another is different from linking a CSS file. When you include a PHP file, the entire code is added to the source file and then the server compiles the codes. So the image files and other resources should be addressed relative to the source document (not the included one). This logic is different in a CSS file and the resource files e.g. a background image is complied relative to the CSS file (Because a CSS may be used in different files hirearchy). So this will work:

<h1>Its header</h1>
<img src="header/img/006-tumblr.png" width="200" height="200"

Footnote: If you want to use header in different files with different hirearchy the solution for the question above is to set BASEURL for your document and setting the resource and anchores relative to the baseurl.

Can I embed a .png image into an HTML page?

There are a few Base64 encoders online to help you with this, and this is probably the best I've seen:

http://www.greywyvern.com/code/php/binary2base64

As that page shows your main options for this are CSS:

div.image {
width:100px;
height:100px;
background-image:url(data:image/png;base64,iVBORwA<MoreBase64SringHere>);
}

Or the <img> tag itself, like this:

<img alt="My Image" src="data:image/png;base64,iVBORwA<MoreBase64SringHere>" />


Related Topics



Leave a reply



Submit