繁体   English   中英

如何使用html文件作为图像文件的来源 <img src=“”> 标签

[英]How to use a html file as a source of image file in <img src=“”> tag

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

例:

index.html的:

<img src="./image.html" >

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文件中的meta标签设置内容标头,也无济于事。 我尝试使用.httaccess文件设置内容标题,但没有用。

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

例:

image.php

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

index.html

<img src="./image.php" >

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

主要思想是能够通过https使用http图片而不会收到混合内容警告。

因此,最好使用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();

这不涉及任何黑客手段,但兼容性有限

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM