控制图像的宽度和高度时,上传图像

control image width and height when upload image

本文关键字:图像 高度 控制      更新时间:2023-09-26

直击要点。当用户使用plupload上传图像时,我想设置图像的宽度和高度的限制。

Letsay:如果宽度:1000像素身高:1000像素其他的你必须上传至少宽度:1000px,高度:1000px的图片

// $(".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();

那么,这可能吗?

你可以很容易地为plupload编写一个过滤器。

这是最小所需宽度的过滤器。将以下代码添加到脚本中。(复制)

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());
});

并将此过滤器添加到您的上传脚本中。

filters : {
            min_width: 700,
        },

Plupload本身不支持此功能(尽管已被请求)。这可能有几个原因,首先是因为你不能在IE中上传之前获得图像尺寸(你可以在其他浏览器中),其次,虽然这对一些使用使用HTML4/5方法的浏览器有效,但我不确定Flash/Silverlight等方法也能够可靠地确定尺寸。

如果你喜欢有限的浏览器,HTML4/5方法只有你应该挂钩到"FilesAdded"事件,例如

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

我最近想做同样的事情,并且能够按照Thom建议的方式实现它。但他对它的局限性的看法是正确的;如果你想添加这个,它只能在现代浏览器中工作,而不能在flash或silverlight运行时中工作。这不是一个大问题,因为我的非html5用户只会在上传之后而不是之前得到错误

我初始化了一个总图像计数变量来跟踪放置在页面上的图像。还有一个变量,用于存储我们想要在阅读完所有照片后删除的照片。

var total_image_count = 0;
var files_to_remove = [];

然后我用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]);
              }
           }
        }
     }

作为旁注,我想要显示图像缩略图,所以这个方法对我很有用。我还没有弄清楚如何获得图像的宽度,而不首先将其附加到DOM。

来源:

上传前先缩略图片:https://stackoverflow.com/a/4459419/686440

访问图像的自然宽度:https://stackoverflow.com/a/1093414/686440

在没有缩略图的情况下访问宽度和高度,您可以这样做:

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);
    }
}