简体   繁体   English

上传图片时控制图片的宽度和高度

[英]control image width and height when upload image

Straight to point. 直指。 I want to set the limit of the width and height of the image when user upload an image using plupload. 我想在用户使用plupload上传图像时设置图像宽度和高度的限制。

Letsay: if width: 1000px height: 1000px else you must upload image with at least width:1000px and height:1000px 假设:如果宽度:1000像素高度:1000像素,则必须上传宽度至少为1000像素,高度为1000像素的图片

// $(".form").validator();
$(function() {
    if($("#uploader").length > 0) {
        var uploader = new plupload.Uploader({
            runtimes : 'html5,flash,silverlight',
            browse_button : 'pickfile',
            container : 'uploader',
            max_file_size : '10mb',
            url : 'design.php?do=upload&ajax=1',
            multiple_queues: false,
            file_data_name: 'design',
            flash_swf_url : www + '/js/plupload.flash.swf',
            silverlight_xap_url : www + '/js/plupload.silverlight.xap',
            filters : [
                {title : "Image files", extensions : "jpg,gif,png,jpeg,bmp"}
            ]

        });

        $('#uploadfiles').click(function(e) {
            if($("#uploader select[name=category]").val() == "") {
                $("#uploader select[name=category]").next('.error-required').show();
                return false;
            }

            uploader.start();
            e.preventDefault();
        });

        uploader.init();

So, is this possible? 那么,这可能吗?

You can easily write a filter for plupload. 您可以轻松编写用于plupload的过滤器。

Here is filter for min required width. 这是最小所需宽度的过滤器。 Add bellow code to your script. 将以下代码添加到脚本中。 (Just copy) (只需复制)

plupload.addFileFilter('min_width', function(maxwidth, file, cb) {
    var self = this, img = new o.Image();

    function finalize(result) {
        // cleanup
        img.destroy();
        img = null;

       // if rule has been violated in one way or another, trigger an error
        if (!result) {
            self.trigger('Error', {
                code : plupload.IMAGE_DIMENSIONS_ERROR,
                message : "Image width should be more than " + maxwidth  + " pixels.",
                file : file
            });
     }
        cb(result);
    }
    img.onload = function() {
        // check if resolution cap is not exceeded
        finalize(img.width >= maxwidth);
    };
    img.onerror = function() {
        finalize(false);
    };
    img.load(file.getSource());
});

And add this filter to your upload script. 并将此过滤器添加到您的上传脚本中。

filters : {
            min_width: 700,
        },

Plupload doesn't support this itself ( although it has been requested ). Plupload本身不支持此功能( 尽管已提出要求 )。 There are probably a couple of reasons for this, firstly because you just can't get the image dimensions before upload in IE ( you can in some other browsers ) and secondly, whilst that would work for some browsers using the using the HTML4/5 methods, I am not sure that the Flash/Silverlight etc. methods would also be able to reliably determine dimensions. 可能有两个原因,首先是因为您无法在IE中上传之前获得图像尺寸( 您可以在其他一些浏览器中 ),其次,这对于使用HTML4 / 5的某些浏览器来说是可行的方法,我不确定Flash / Silverlight等方法是否也能够可靠地确定尺寸。

If you were happy with limited browser, HTML4/5 methods only you should hook into the "FilesAdded" event eg 如果您对有限的浏览器感到满意,则仅应使用HTML4 / 5方法,并应挂入“文件添加”事件,例如

uploader.bind('FilesAdded', function(up, files) {
  //Get src of each file, create image, remove from file list if too big
});

I recently wanted to do the same thing, and was able to achieve it the way Thom was suggesting. 我最近想做同样的事情,并且能够按照Thom的建议来实现。 He was correct on it's limitation though; 不过他对局限性是正确的。 if you want to add this, it will only work in modern browsers and not in the flash or silverlight runtimes. 如果要添加它,它将仅在现代浏览器中运行,而不能在Flash或Silverlight运行时中运行。 This is not a huge issue, as my non-html5 users will just get an error after upload, rather than before. 这不是一个大问题,因为我的非html5用户只会上传后而不是之前收到错误消息。

I initialized a total image count variable to keep track of the images placed on the page. 我初始化了一个总图像计数变量,以跟踪放置在页面上的图像。 Also a vairable to store photos we want to delete after we read them all. 也可以存储我们要在阅读完所有照片后删除的照片。

var total_image_count = 0;
var files_to_remove = [];

Then I read the pending files with FileReader(), place them on the page, and get their width 然后,我使用FileReader()读取待处理的文件,将其放置在页面上,并获取其宽度

init:{
        FilesAdded: function(up, files) {
           if (uploader.runtime == "html5"){
              files = jQuery("#"+uploader.id+"_html5")[0].files
              console.log(files);
              for (i in files){

                 //create image tag for the file we are uploading
                 jQuery("<img />").attr("id","image-"+total_image_count).appendTo("#upload-container");

                 reader_arr[total_image_count] = new FileReader();

                 //create listener to place the data in the newly created 
                 //image tag when FileReader fully loads image.
                 reader_arr[total_image_count].onload = function(total_image_count) {
                    return function(e){
                       var img = $("#image-"+total_image_count);
                       img.attr('src', e.target.result);
                       if ($(img)[0].naturalWidth < 1000){

                          files_to_remove.push(files[i]); //remove them after we finish reading in all the files
                          //This is where you would append an error to the DOM if you wanted.
                          console.log("Error. File must be at least 1000px");
                       }
                    }
                 }(total_image_count);

                 reader_arr[total_image_count].readAsDataURL(files[i]);

                 total_image_count++;
              }
              for (i in files_to_remove){
                 uploader.removeFile(files_to_remove[i]);
              }
           }
        }
     }

As a side note, I was wanting to show image thumbnails anyway, so this method works great for me. 附带说明一下,无论如何我都想显示图像缩略图,因此这种方法对我来说非常有用。 I have not figured out how to get an image's width without first appending it to the DOM. 我还没有弄清楚如何在不先将图像附加到DOM的情况下获得图像的宽度。

Sources: 资料来源:

Thumbnail an image before upload: https://stackoverflow.com/a/4459419/686440 缩略图图片上传之前: https : //stackoverflow.com/a/4459419/686440

Accessing image's natural width: https://stackoverflow.com/a/1093414/686440 访问图像的自然宽度: https//stackoverflow.com/a/1093414/686440

to access width and heigth without thumbnail an image you can do this: 要访问没有缩略图的宽度和高度,可以执行以下操作:

uploader.bind('FilesAdded', function(up, files) {
    files = jQuery("#"+uploader.id+"_html5").get(0).files;
    jQuery.each(files, function(i, file) {
        var reader = new FileReader();
        reader.onload = (function(e) { 
            var image = new Image();
            image.src = e.target.result;

                image.onload = function() {
                    // access image size here using this.width and this.height
                }
            };

        });

        reader.readAsDataURL(file);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM