2015-01-16 66 views
0

工作小提琴:http://jsfiddle.net/nbv8mb4a/如何获得高度和宽度或用户本地图像

尝试小提琴:http://jsfiddle.net/3m0zekyj/

我的工作小提琴允许用户上传前看到的图片。接下来我要做的是获取图像的高度和宽度,以便至少一边是160px,否则将是160px或更大的图像将缩放。

低于160高度或宽度的图像将不被允许但是我卡在我的轨道上以获得宽度和高度。我的工作代码到目前为止在下面;

var wrapper = $('<div/>').css({height:0,width:0,'overflow':'hidden'}); 
var fileInput = $(':file').wrap(wrapper); 

fileInput.change(function(){ 
    readURL(this); 
}) 

$('#file').click(function(){ 
    fileInput.click(); 
}).show(); 

function readURL(input) { 
    $('#blah').hide(); 
    if (input.files && input.files[0]) { 
     var goUpload = true; 
     var uploadFile = input.files[0]; 
     if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(uploadFile.name)) { 
      $('#file').effect("shake"); 
      $('#file').text('You must select an image file only'); 
      setTimeout(function() { $('#file').text('Choose file');},5000); 
      goUpload = false; 
     } 
     if (uploadFile.size > 2000000) { // 2mb 
      //common.notifyError('Please upload a smaller image, max size is 2 MB'); 
      $('#file').text('Please upload a smaller image, max size is 2 MB'); 
      setTimeout(function() { $('#file').text('Choose file');},5000); 
      goUpload = false; 
     } 
     if (goUpload) { 
      $('#file').text("Uploading "+uploadFile.name); 
      var reader = new FileReader(); 
      reader.onload = function (e) { 
       $('#blah').attr('src', e.target.result).show(); 
       $('#file').text(uploadFile.name); 
      } 
      reader.readAsDataURL(uploadFile); 
     } 
    } 
} 

一些进展:http://jsfiddle.net/pe8wg9kx/

+0

你缺少在我们的代码尝试这么多的事情要同时复制更多的智能和粘贴亲爱的! –

+0

您可以用这种方式设置图像对象的文件来源:var img = new Image(); img.onload = function(){ alert(this.width +'x'+ this.height); } img.src ='http://www.google.com/intl/zh-CN/ALL/images/logo.gif'; – Blauharley

+0

@ surajrawat我不是最好的,我一直在这个相当一段时间,这是迄今为止这部分最好的进展... –

回答

1

在你试图拨弄你在呼唤:

width = this.width(); 
height = this.height(); 

,这是不确定的。
首先分配SRC属性,然后读取宽度和高度是这样的:

$('#blah').attr('src', e.target.result).show(); 
width = $('#blah').width(); 
height = $('#blah').height(); 
+0

谢谢[更新的小提琴](http://jsfiddle.net/3m0zekyj/ 1 /)。现在扭转,所以最小宽度/高度是100px,然后居中图像。 –

+0

等等,我的小提琴不起作用,它只是显示图像抱歉! –

+0

明白了吧[这里](http://jsfiddle.net/0dexuoxn/) –

相关问题