javascript 验证图像文件类型/文件大小、裁剪、调整大小然后上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13909415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:08:42  来源:igfitidea点击:

Validate image filetype/filesize, crop, resize & then upload

javascriptjqueryflashclient

提问by Rajat Gupta

I'm looking for a client side solution to validate whether the image being uploaded is of accepted file type, file size & then crop the image as directed by user, re-size it to fit within some particular dimensions & then upload the re-sized & optimized image to server.

我正在寻找客户端解决方案来验证上传的图像是否为可接受的文件类型、文件大小,然后按照用户的指示裁剪图像,重新调整大小以适应某些特定尺寸,然后上传重新 -调整大小和优化的图像到服务器。

Are there any well known open-source libraries that can help me implement this ? (Multiple files uploading not needed). I'm not wanting to implement this myself & looking for a library that can provide a cross browser compatible solution with fallbacks for old/unsupported browsers.

是否有任何众所周知的开源库可以帮助我实现这一点?(不需要上传多个文件)。我不想自己实现这个并寻找一个可以提供跨浏览器兼容解决方案的库,并为旧的/不受支持的浏览器提供回退。

I came across plupload & agile uploader, but those don't help in cropping images as per user directions.

我遇到了 plupload 和敏捷上传器,但这些都无助于按照用户指示裁剪图像。



Using jQuery 1.7. Open to add other libraries too in case required.

使用 jQuery 1.7。如果需要,也可以打开以添加其他库。

回答by Ahmed Sabry

peace be upon you brother

兄弟,愿你平安

i'm using what you want in my project but no ( resize photo as i put custom size for images )

我在我的项目中使用你想要的但没有(调整照片大小,因为我为图像设置了自定义大小)

i using ( imgareaselect ) to crop photo

我使用( imgareaselect )来裁剪照片

but i don't remember the site of it, maybe: http://odyniec.net/projects/imgareaselect/examples.html

但我不记得它的网站了,也许:http: //odyniec.net/projects/imgareaselect/examples.html

if is it that site right, i'm using this code

如果那个网站是对的,我正在使用这个代码

   var x1 = null, y1 = null, w = null, h = null, Signal = null, object=null;

   function preview(img, selection) {
    var img = {
        url: jQuery("#image").attr("src"),
        width: jQuery("#image").width(),
        height: jQuery("#image").height()
    }

    var scaleX = 128 / selection.width;  // 128 = my custom size ;)
    var scaleY = 128 / selection.height; 
    $(".avatar-box img").replaceWith('<img id="thumbnail" src="'+img.url+'" class="preview" border="0"/>');


    $('#thumbnail').css({ 
      width: Math.round(scaleX * img.width) + 'px', 
      height: Math.round(scaleY * img.height) + 'px',
      marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px', 
      marginTop: '-' + Math.round(scaleY * selection.y1) + 'px' 
    });

    x1 = selection.x1; y1 = selection.y1; w = selection.width; h = selection.height;
   }
$(window).ready(function () {
 $('#image').imgAreaSelect({ aspectRatio: '1:1', onSelectChange: preview });
});

and to check the size and type: i use also this script

并检查大小和类型:我也使用这个脚本

   $("form").submit(function(){
     var OrgFile = $(this).find("[type=file]"),
         FileName = OrgFile.val(),
         FileExtension = FileName.split('.').pop().toLowerCase();
         if(FileName.indexOf(".")==-1 || FileExtension != "jpg" && FileExtension != "jpeg" && FileExtension != "png" && FileExtension != "gif" ){ // Curstom File Extension
          alert("This isn't a Photo !");
          return false;
         }else
         if((OrgFile[0].files[0].size/1024/1024) > (1)){ // Max Photo Size 1MB
          alert("You Photo is too big !");
          return false;
         }else{
          alert("every thing Fine :)");
          return true;
         }
   });

Then if the client submit the cropped image

然后如果客户端提交裁剪的图像

  $('#create_thumbnail').submit(function() {
    $.ajax({
     type : "POST",
     url : "resize.php",
     data : {logged_code: logged_code,x1: x1,y1: y1,w: w,h: h},
     success: function(data) {}
    });
    return false;
  });

And resize.php file

和 resize.php 文件

    function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale){
        list($imagewidth, $imageheight, $imageType) = getimagesize($image);
        $imageType = image_type_to_mime_type($imageType);
        $newImageWidth = ceil($width * $scale);
        $newImageHeight = ceil($height * $scale);
        $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
        switch($imageType) {
            case "image/gif":
                $source=imagecreatefromgif($image); 
                break;
            case "image/pjpeg":
            case "image/jpeg":
            case "image/jpg":
                $source=imagecreatefromjpeg($image); 
                break;
           case "image/png":
            case "image/x-png":
                imagealphablending($newImage, false);
                imagesavealpha($newImage, true);  
                $source=imagecreatefrompng($image); 
                break;
        }
        imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,$newImageHeight,$width,$height);
        switch($imageType) {
            case "image/gif":
                imagegif($newImage,$thumb_image_name); 
                break;
            case "image/pjpeg":
            case "image/jpeg":
            case "image/jpg":
                imagejpeg($newImage,$thumb_image_name,100); 
                break;
            case "image/png":
            case "image/x-png":
                imagepng($newImage,$thumb_image_name);  
                break;
      }
        chmod($thumb_image_name, 0777);
        return $thumb_image_name;
    }

i hope that i help you and understand your question,

我希望我能帮助你并理解你的问题,

please vopte my answer that i want to join php chat room to find one help me in a problem

请投票我的回答,我想加入 php 聊天室以找到一个帮助我解决问题的人

sorry for my bad english i'm speaking arabic

抱歉我的英语不好,我说的是阿拉伯语

回答by Rick Deckard

There are several separate things here:

这里有几个单独的东西:

  • Validating image/file type. This can be done at the client side, but you will need to do it at the server again for security. For a file input that only accepts images, you can use:

    <input type="file" accept='image/*'>
    
  • Letting the user crop the image. There are several libraries here, the most prominent one being Jcrop. But there are alternatives, like imgareaselect, jqCrop and jquery-cropbox (I created and mantain the jquery-cropbox). See here for a very minimal example on how you can get started with one or two lines of jquery.

  • 验证图像/文件类型。这可以在客户端完成,但为了安全起见,您需要再次在服务器上完成。对于只接受图像的文件输入,您可以使用:

    <input type="file" accept='image/*'>
    
  • 让用户裁剪图像。这里有几个库,最突出的一个是 Jcrop。但是还有其他选择,比如 imgareaselect、jqCrop 和 jquery-cropbox(我创建并维护了 jquery-cropbox)。有关如何开始使用一两行 jquery 的非常简单的示例,请参见此处。

http://acornejo.github.io/jquery-cropbox/

http://acornejo.github.io/jquery-cropbox/

  • Doing the actual cropping at the client. This requires HTML5, and therefore won't work with older version of internet explorer. In particular you will need the canvas api, and possibly the file api (to serve the files). jquery-cropbox can also do this for you through the getBloband getDataURLmethods. If you want to do it by hand, take a look here:
  • 在客户端进行实际裁剪。这需要 HTML5,因此不适用于旧版本的 Internet Explorer。特别是您将需要画布 api,可能还需要文件 api(用于提供文件)。jquery-cropbox 也可以通过getBlobgetDataURL方法为您做到这一点。如果您想手动完成,请看这里:

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D

  • Uploading the image. There are plenty of scripts for uploading images out there, take your pick. If you are using jquery-cropbox, then you can use jquery to handle the upload to your server like this (uploading client generated form data like this will also require an HTML5 compliant browser).

    var blob = $('#yourimage').data('cropbox').getBlob();
    var fd = new FormData();
    fd.append('file', blob);
    
    $.ajax({
        type: 'POST',
        url: 'http://yourwebsite.com/handle_uploads',
        data: fd,
        cache: false,
        contentType: false,
        processData: false,
        success: function(data){
          alert('upload succeeded');
        },
        error: function () {
          alert('upload failed');
        }
    });
    

    },

  • 上传图片。有很多用于上传图像的脚本,您可以选择。如果您使用的是 jquery-cropbox,那么您可以使用 jquery 来处理上传到您的服务器的操作(像这样上传客户端生成的表单数据也需要一个 HTML5 兼容的浏览器)。

    var blob = $('#yourimage').data('cropbox').getBlob();
    var fd = new FormData();
    fd.append('file', blob);
    
    $.ajax({
        type: 'POST',
        url: 'http://yourwebsite.com/handle_uploads',
        data: fd,
        cache: false,
        contentType: false,
        processData: false,
        success: function(data){
          alert('upload succeeded');
        },
        error: function () {
          alert('upload failed');
        }
    });
    

    },

回答by Luke Merrett

Try using Fine Uploaderfor the client side validation and uploading; with JCropfor the cropping of the image afterwards.

尝试使用Fine Uploader进行客户端验证和上传;使用JCrop之后对图像进行裁剪。

Fine uploader is excellent for restricting the size and file type (See here) on the client side; however it does depend on which browsers you need to support (I believe IE7 won't allow you to validate on the client side like this).

Fine Uploader 非常适合在客户端限制大小和文件类型(请参阅此处);但是它确实取决于您需要支持哪些浏览器(我相信 IE7 不允许您像这样在客户端进行验证)。

Whilst JCrop is an easy to implement cropping tool which supports aspect ratios and converting images between their display and actual sizes.

虽然 JCrop 是一种易于实现的裁剪工具,它支持纵横比并在其显示和实际尺寸之间转换图像。

回答by Eric

Resizing can be done with FileReader and a canvas. Create a canvas with wanted size.

可以使用 FileReader 和画布来调整大小。创建具有所需大小的画布。

Load the image. Then use the canvas.toDataURL(fileType) to get the file content as base64

加载图像。然后使用 canvas.toDataURL(fileType) 获取文件内容为 base64

回答by Techie

jQuery Ajax code

jQuery Ajax 代码

jQuery('document').ready(function(){

    var input = document.getElementById("imagefile");
    var formdata = false;
    if (window.FormData) {
        formdata = new FormData();
    }

    input.addEventListener("change", function (evt) {

        var i = 0, len = this.files.length, img, reader, file;

        for ( ; i < len; i++ ) {
            file = this.files[i];

            //validation to check whether uploaded files are images
            if (!!file.type.match(/image.*/)) {
                if ( window.FileReader ) {
                    reader = new FileReader();
                    reader.onloadend = function (e) { 
                    };
                    reader.readAsDataURL(file);
                }


                if (formdata) {
                    //send the ajax query to upload the file(s)
                    jQuery.ajax({
                        url: "upload.php",
                        type: "POST",
                        data: formdata,
                        processData: false,
                        contentType: false,
                        success: function (result) {
                            jQuery('div#response').html("Successfully uploaded").fadeOut();
                        }
                    });
                }
            }
            else
            {
                alert('Not a vaild image!');
            }   
        }

    }, false);


});

HTML Code

HTML代码

<form enctype="multipart/form-data">
<input id="imagefile" type="file" name="image" accept="image/*"/ />
</form>

What above code will do for you is, once you upload the file(s) it will 1st of validate the type of the image and upload it via ajax for you. You can do multiple file uploadsif you need. If you ever wonder what FormDatadoes,

上面的代码将为您做的是,一旦您上传文件,它将首先验证图像的类型并通过ajax为您上传。如果需要,您可以进行多个文件上传。如果你想知道什么FormData

The FormDataobject lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to "multipart/form-data".

FormData对象允许您编译一组键/值对以使用 XMLHttpRequest 发送。它主要用于发送表单数据,但可以独立于表单使用以传输密钥数据。如果表单的编码类型设置为“multipart/form-data”,则传输的数据与表单的 submit() 方法用于发送数据的格式相同。

What addEventListener does for you is,

addEventListener 为你做的是,

addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, the document itself, a window, or an XMLHttpRequest.

addEventListener() 在单个目标上注册单个事件侦听器。事件目标可以是文档中的单个元素、文档本身、窗口或 XMLHttpRequest。

You can use upload.phpto upload the file(s) at the server level.

您可以使用upload.php在服务器级别上传文件。

If you want to have the this functionality in a plugin you can extend the plugin with the above code and it will not brick your plugin because this is a very straight forward code snippet which gets the job done. I have successfully integrated the code to a plugin with no issues at all.

如果你想在插件中拥有这个功能,你可以用上面的代码扩展插件,它不会让你的插件变砖,因为这是一个非常简单的代码片段,可以完成工作。我已成功将代码集成到插件中,完全没有问题。

this link will show you how to validate for the file size. JavaScript file upload size validation

此链接将向您展示如何验证文件大小。JavaScript 文件上传大小验证

Re-size it to fit within some particular dimensions javascript Image Resize

重新调整大小以适应某些特定尺寸 javascript Image Resize

How to resize images proportionally / keeping the aspect ratio?

如何按比例调整图像大小/保持纵横比?

These link should help for you. I'm not going to integrate all into one because to maintain the simplicity of the code so you can understand easily.

这些链接应该对您有所帮助。我不会将所有内容整合为一个,因为为了保持代码的简单性,以便您可以轻松理解。

If you have any issues let me know.

如果您有任何问题,请告诉我。

回答by Kashif Naseem

Please have a look at this library

请看看这个图书馆

and this isdocumentation page where you can set max resize values,

这是文档页面,在这里你可以设置最大调整大小值,

<maxwidth>800</maxwidth>
<maxheight>500</maxheight>
<minwidth>100</minwidth>
<minheight>70</minheight>  

回答by Vinoth Babu

Please use the following to check filesize on client end:

请使用以下命令检查客户端的文件大小:

<script type="text/javascript">
    $('#image-file').bind('change', function() {
        alert('This file size is: ' + this.files[0].size/1024/1024 + "MB");
    });
</script>

If you need a plugin type to use for the entire project you can take a look at this.

如果你需要一个插件类型来用于整个项目,你可以看看这个

If you are looking for a multiple uploader please use this.

如果您正在寻找多个上传者,请使用这个

回答by user1353468

As for the file type and size:

至于文件类型和大小:

var fileUpload = $(':file[id="fileUploadId"]');
var fileName = $(fileUpload).val();
// Checking type:
if(fileName.indexOf('.jpg') || fileName.indexOf('.gif')){/* Accepted types */}

// Check size
if($(fileUpload).size() <= yourAcceptedSize) {/* Accepted size */}   

回答by toto

I have an idea. You can try using this plugin to upload.

我有个主意。您可以尝试使用此插件进行上传。

http://des.delestesoft.com:8080/?go=2

http://des.delestesoft.com:8080/?go=2

when you define the attributes: post variables->

定义属性时:发布变量->

variables:{
            sessionID:"abcdefg",
            width:$("#myimage").width(),
            height:$("#myimage").heigth()
        },

in the server side: you get the file and change the size image according the post variables.

在服务器端:您获取文件并根据帖子变量更改大小图像。