我想按照下面的代碼在JavaScript中加載圖像。訪問JavaScript中的圖像對象
var img = new Image();
img.src="http://somesite.com/abc.gif";
我想訪問「img」中的字節。是否有可能以二進制形式訪問圖像?
我想按照下面的代碼在JavaScript中加載圖像。訪問JavaScript中的圖像對象
var img = new Image();
img.src="http://somesite.com/abc.gif";
我想訪問「img」中的字節。是否有可能以二進制形式訪問圖像?
顯然JavaScript不能將圖像轉換成二進制形式的直接,不過您可以用一種變通方法做到這一點:
<script>
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
var data = canvas.toDataURL("image/jpeg");
alert(data);
};
img.src = "http://localhost/MvcApplication3/test.png";
</script>
<script>
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
var data = canvas.toDataURL("image/jpeg");
alert(data);
};
img.src = "http://somesite.com/abc.gif";
</script>
您可以嘗試以下代碼:
/fileInput is an HTMLInputElement: <input type="file" id="myfileinput" multiple>
var fileInput = document.getElementById("myfileinput");
// files is a FileList object (similar to NodeList)
var files = fileInput.files;
// object for allowed media types
var accept = {
binary : ["image/png", "image/jpeg"],
text : ["text/plain", "text/css", "application/xml", "text/html"]
};
var file;
for (var i = 0; i < files.length; i++) {
file = files[i];
// if file type could be detected
if (file !== null) {
if (accept.binary.indexOf(file.mediaType) > -1) {
// file is a binary, which we accept
var data = file.getAsBinary();
} else if (accept.binary.indexOf(file.mediaType) > -1) {
// file is of type text, which we accept
var data = file.getAsText();
// modify data with string methods
}
}
}
欲瞭解更多參考查看here