簡體   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