dongping1689 2010-02-24 20:44
浏览 48
已采纳

如何在单个HTML / PHP文件中嵌入图像?

I am creating a lightweight, single-file database administration tool and I would like to bundle some small icons with it. What is the best way to embed images in a HTML/PHP file?

I know a method using PHP where I would call the same file with a GET parameter that would output hardcoded binary data with the correct header, but that seems a bit complicated.

Can I use something to pass the image directly in a CSS background-image declaration? This would allow me to utilize the CSS sprite technique.

Browser support isn't an issue here, so more exotic methods are welcome also.

EDIT

Does someone have a link/example to how to generate Data URL's properly with PHP? I'd figure echo 'data:image/png;base64,'.base64_encode(file_get_contents('image.png')) would suffice but I could be wrong.

  • 写回答

3条回答 默认 最新

  • douzhenao6515 2010-02-24 20:49
    关注

    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" />
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题