2015-01-16 2 views
0

Рабочая JSFiddle, прежде чем пытаться реализовать: http://jsfiddle.net/qa9m7t33/Изменение размера предварительного просмотра изображения не работает

После попытки реализации: http://jsfiddle.net/z1k538sm/

Я нашел, как изменить размер изображения, однако я считаю, что это не пример для того, что до загрузки и я довольно новичок в этом. То, что я считаю ошибочным, - это переменная;

var width = e.target.result.width(); // Current image width 
var height = e.target.result.height(); // Current image height 

У меня также возникла проблема с центрированием текста в поле для загрузки.

Обновлено Fiddle: http://jsfiddle.net/m5jLf259/

ответ

1

Не совсем Js ответ на это, но добавив высоту строки CSS к элементу

#file { 
    line-height: 37px; 
} 

будет получить работу, я думаю, если вы хотите, чтобы это было jQuery вы могли бы сделать

$('#file').css('line-height',$('#file').height() + 'px'); 

Что касается первой части вашей проблемы, я не мог разобрать вопрос, извините.

Edit: для первой части попробовать это:

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) { 
       var img = new Image; 
       img.onload = function() { 
        var maxWidth = 100; // Max width for the image 
       var maxHeight = 100; // Max height for the image 
       var ratio = 0; // Used for aspect ratio 
       var width = this.width; // Current image width 
       var height = this.height; // Current image height 

       // Check if the current width is larger than the max 
       if (width > maxWidth) { 
        ratio = maxWidth/width; // get ratio for scaling image 
        $('#blah').css("width", maxWidth); // Set new width 
        $('#blah').css("height", height * ratio); // Scale height based on ratio 
        height = height * ratio; // Reset height to match scaled image 
       } 



       // Check if current height is larger than max 
       if (height > maxHeight) { 
        ratio = maxHeight/height; // get ratio for scaling image 
        $('#blah').css("height", maxHeight); // Set new height 
        $('#blah').css("width", width * ratio); // Scale width based on ratio 
        width = width * ratio; // Reset width to match scaled image 
       } 
       $('#blah').attr('src', this.src).show(); 
       $('#file').text(uploadFile.name); 

       }; 
       img.src = reader.result; 

      } 
      reader.readAsDataURL(uploadFile); 
     } 
    } 
} 

Вы не должны иметь ту часть, где он говорит:

47   var width = uploadFile.width(); // Current image width 
48   var height = uploadFile.height(); // Current image height 

дважды, потому что вы просто расстегивать свою работу от предыдущий IF.

Также кажется, что FileReader() не может получить свойства размера изображения, а вместо этого имеет FileReader, создать объект изображения, а затем сделать загрузку объекта Object активным.

+0

+! Для первого вопроса: В основном, проверьте мою [рабочую скрипту] (http://jsfiddle.net/qa9m7t33/), которая при загрузке файла, который он просматривает, и я пытаюсь масштабировать изображение, а затем центрировать изображение в выделенном размере пособие –

+0

Это должно было сказать +1 кстати. –

Смежные вопросы