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 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决