JavaScript擷取圖片的真實尺寸大小樣本

來源:互聯網
上載者:User

最簡單的基本jquery外掛程式擷取教程

 代碼如下 複製代碼

var img = $("#img_id"); // Get my img elem
var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues
    .attr("src", $(img).attr("src"))
    .load(function() {
        pic_real_width = this.width;   // Note: $(this).width() will not
        pic_real_height = this.height; // work for in memory images.
 });

例子,如果你覺得jquery外掛程式包大了,我們可以使用js來實現

 代碼如下 複製代碼

<img src="yun_qi_img/xxx.jpg" id="imgs" onload="adapt();"/>

function adapt(){
var tableWidth = $("#imgTable").width(); //表格寬度
var img = new Image();
img.src =$('#imgs').attr("src") ;
var imgWidth = img.width; //圖片實際寬度
if(imgWidth<tableWidth){
$('#imgs').attr("style","width: auto");
}else{
$('#imgs').attr("style","width: 100%");
}
}

css代碼

<style type="text/css">
<!--
img{
max-width:100%;height:auto;
}
-->
</style>

如果你想擷取遠程機器圖片我們可以用下面代碼。

 代碼如下 複製代碼

<title>JavaScript擷取遠程圖片大小</title>
<script>
var img=null;
function s()
{
if(img)img.removeNode(true);
img=document.createElement("img");
img.style.position="absolute";
img.style.visibility="hidden";
img.attachEvent("onreadystatechange",orsc);
img.attachEvent("onerror",oe);
document.body.insertAdjacentElement("beforeend",img);
img.src=inp.value;
}
function oe()
{
alert("cant load img");
}
function orsc()
{
if(img.readyState!="complete")return false;
alert(img.offsetHeight+":"+img.offsetWidth);
}
</script>
<input id=inp style="width:400" value="/images/logo.gif">
<button onclick="s()">擷取</button>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.