【问题标题】:How to use a html file as a source of image file in <img src=""> tag如何在 <img src=""> 标签中使用 html 文件作为图像文件的来源
【发布时间】:2017-06-06 07:07:46
【问题描述】:

我正在尝试使用 html 文件作为 &lt;img src=""&gt; 标记中的图像文件的来源,以避免在使用 http 图像时通过 https 发出混合内容警告。

示例:

index.html:

&lt;img src="./image.html" &gt;

image.html:

function getBase64FromImageUrl(url) {
      var img = new Image();
    
      img.setAttribute('crossOrigin', 'anonymous');
    
      img.onload = function () {
          var canvas = document.createElement("canvas");
          canvas.width =this.width;
          canvas.height =this.height;
    
          var ctx = canvas.getContext("2d");
          ctx.drawImage(this, 0, 0);
    
          var dataURL = canvas.toDataURL("image/png");
          dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
          document.write(dataURL);
      };
    
      img.src = url;
    }
    getBase64FromImageUrl("http://www.w3schools.com/css/trolltunga.jpg");
<meta http-equiv="Content-type" content="image/png"/>


<!--
I do not want to add any child tags to the body in order to display image from this base64 data. i just want to display using the content headers.
-->

当我尝试打开 Html 文件时,我正在尝试使用我现在使用 javascript 转储到 html 文件中的图像数据,我看到一个字符串,该字符串表示包含抓取的图形数据但不是实际的编码 URL图像作为标题未设置,即使我尝试在 html 文件中使用元标记设置内容标题,也没有任何帮助。我尝试使用 .httaccess 文件设置内容标题,但没有用。

我知道可以使用任何服务器端脚本,因为我们设置的内容标头与对 http 请求的响应一起从服务器发送。

示例:

image.php

<?php
  header("Content-Type: image/png");
  readfile("www.example.com/img.png");
?>

index.html

&lt;img src="./image.php" &gt;

我可以用 php 做到这一点,但我实际上想使用 html 和 javascript。

主要想法是能够在 https 上使用 http 图像而不会收到混合内容警告。

【问题讨论】:

  • use a html file as a source of image - 你不能。 to avoid mixed-content warning - 你也不能那样做。防止混合内容是一项安全功能。如果您想自己避免使用它,请找到 1990 年的浏览器并使用它
  • @JaromandaX 使用 PHP 可以避免混合内容警告。我已经这样做了。现在我正在尝试使用 HTML 和 javascript 来实现相同的功能。你可以自己检查一下:dukaanbabu.com/beta/api/image.php
  • 是吗?好吧,您已经回答了自己的问题。干得好。
  • 您不能使用meta 元素在客户端设置Content-Type HTTP 标头,也不能使用meta 元素以其他方式更改资源的内容类型。浏览器只会使用 Web 服务器在响应中发送的真实 Content-Type HTTP 标头的值(我假设是 text/html)。或者,如果由于某种原因 Web 服务器根本没有在响应中发送任何 Content-Type,那么您仍然无法仅通过使用 meta 元素让浏览器将其视为其他内容类型.

标签: javascript jquery html https mixed-content


【解决方案1】:

因此,您最好处理 XHR 和 FileReader API,如下所示:

var b64xhr = new XMLHttpRequest();
    b64xhr.open( "GET", url );
    b64xhr.responseType = "blob";
    b64xhr.onload = function (){
        if (b64xhr.status===200){
            reader.readAsDataURL( b64xhr.response );
        }
        else if (b64xhr.status===404){
            // error
        }
    };
var reader = new FileReader();
    reader.onloadend = function () {
        console.log (reader.result );
    };
b64xhr.send();

这不涉及任何形式的破解,但兼容性有限

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 2018-06-23
    • 2011-03-26
    • 2015-04-25
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    相关资源
    最近更新 更多