当前我有以下可以上传图像:
<%= file_field "form_x", "image", accept: 'image/png,image/gif,image/jpeg' %>
在我的方法中,我可以使用此
访问图像params[:form_x][:image]
并通过params[:form_x][:image].size
读取图像的size
。但是如何通过像素检查图像的高度和宽度呢?我希望能够按大小以及高度和宽度限制图像。
正确的方法是在客户端进行。您需要一些JavaScript,这是一个示例。
您无法从参数获取图像宽度和Heigth。
html
<input id="image" name="img" type="file" />
/* */
<img src="#" alt="This image is going to load" id="image_on_load" />
<p id='image_info_width'> </p>
<p id='image_info_heigth'> </p>
JS代码:
// The upload listner function
$('#image').on('change', function() {
var img = document.getElementById('image_on_load');
var reader = new FileReader();
// add uploaded image to the img element
reader.onloadend = function() {
$('#image_on_load').prop('src', reader.result)
}
reader.readAsDataURL(this.files[0]);
// listen onload event and get dimension
img.onload = function(image) {
$('#image_info_width').text('Width: ' + image.target.width)
$('#image_info_heigth').text('Height: ' + image.target.height)
// here you able to upload or reject
// file accourding to dimension
}
});
在此示例中,图像已上传,您可以获得宽度和高度。
JSFIDDLE
阅读导轨中的JS的工作方式 7 Must-Reads about JavaScript with Ruby on Rails