Image resize before upload

后端 未结 9 1499
闹比i
闹比i 2020-11-28 03:09

I need to provide a means for a user to upload photos to their web site in jpeg format. However, the photos are very large in original size, and I would like to make the re

相关标签:
9条回答
  • 2020-11-28 03:27

    In 2011, we can know do it with the File API, and canvas. This works for now only in firefox and chrome. Here is an example :

    var file = YOUR_FILE,
        fileType = file.type,
        reader = new FileReader();
    
    reader.onloadend = function() {
      var image = new Image();
          image.src = reader.result;
    
      image.onload = function() {
        var maxWidth = 960,
            maxHeight = 960,
            imageWidth = image.width,
            imageHeight = image.height;
    
        if (imageWidth > imageHeight) {
          if (imageWidth > maxWidth) {
            imageHeight *= maxWidth / imageWidth;
            imageWidth = maxWidth;
          }
        }
        else {
          if (imageHeight > maxHeight) {
            imageWidth *= maxHeight / imageHeight;
            imageHeight = maxHeight;
          }
        }
    
        var canvas = document.createElement('canvas');
        canvas.width = imageWidth;
        canvas.height = imageHeight;
    
        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
    
        // The resized file ready for upload
        var finalFile = canvas.toDataURL(fileType);
      }
    }
    
    reader.readAsDataURL(file);
    
    0 讨论(0)
  • 2020-11-28 03:28

    You can resize the image in the client-side before uploading it using an image processing framework.

    Below I used MarvinJ to create a runnable code based on the example in the following page: "Processing images in client-side before uploading it to a server"

    Basically I use the method Marvin.scale(...) to resize the image. Then, I upload the image as a blob (using the method image.toBlob()). The server answers back providing a URL of the received image.

    /***********************************************
     * GLOBAL VARS
     **********************************************/
    var image = new MarvinImage();
    
    /***********************************************
     * FILE CHOOSER AND UPLOAD
     **********************************************/
     $('#fileUpload').change(function (event) {
    	form = new FormData();
    	form.append('name', event.target.files[0].name);
    	
    	reader = new FileReader();
    	reader.readAsDataURL(event.target.files[0]);
    	
    	reader.onload = function(){
    		image.load(reader.result, imageLoaded);
    	};
    	
    });
    
    function resizeAndSendToServer(){
      $("#divServerResponse").html("uploading...");
    	$.ajax({
    		method: 'POST',
    		url: 'https://www.marvinj.org/backoffice/imageUpload.php',
    		data: form,
    		enctype: 'multipart/form-data',
    		contentType: false,
    		processData: false,
    		
    	   
    		success: function (resp) {
           $("#divServerResponse").html("SERVER RESPONSE (NEW IMAGE):<br/><img src='"+resp+"' style='max-width:400px'></img>");
    		},
    		error: function (data) {
    			console.log("error:"+error);
    			console.log(data);
    		},
    		
    	});
    };
    
    /***********************************************
     * IMAGE MANIPULATION
     **********************************************/
    function imageLoaded(){
      Marvin.scale(image.clone(), image, 120);
      form.append("blob", image.toBlob());
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://www.marvinj.org/releases/marvinj-0.8.js"></script>
    <form id="form" action='/backoffice/imageUpload.php' style='margin:auto;' method='post' enctype='multipart/form-data'>
    				<input type='file' id='fileUpload' class='upload' name='userfile'/>
    </form><br/>
    <button type="button" onclick="resizeAndSendToServer()">Resize and Send to Server</button><br/><br/>
    <div id="divServerResponse">
    </div>

    0 讨论(0)
  • 2020-11-28 03:31

    You have several options:

    1. Java
    2. ActiveX (only on windows)
    3. Silverlight
    4. Flash
    5. Flex
    6. Google Gears (the most recent version is capable of resizing and drag and drop from your desktop)

    I've done a lot of research looking for a similar solution to what you have described and there a lot of solutions out there that vary a lot in quality and flexibility.

    My suggestion is find a solution which will do 80% of what you need and customize it to suit your needs.

    0 讨论(0)
  • 2020-11-28 03:33

    I think you need Java or ActiveX for that. For example Thin Image Upload

    0 讨论(0)
  • 2020-11-28 03:36

    Pure JavaScript solution. My code resizes JPEG by bilinear interpolation, and it doesn't lose exif.

    https://github.com/hMatoba/JavaScript-MinifyJpegAsync

    function post(data) {
        var req = new XMLHttpRequest();
        req.open("POST", "/jpeg", false);
        req.setRequestHeader('Content-Type', 'image/jpeg');
        req.send(data.buffer);
    }
    
    function handleFileSelect(evt) {
        var files = evt.target.files;
    
        for (var i = 0, f; f = files[i]; i++){
            var reader = new FileReader();
            reader.onloadend = function(e){
                MinifyJpegAsync.minify(e.target.result, 1280, post);
            };
            reader.readAsDataURL(f);
        }
    }
    
    document.getElementById('files').addEventListener('change', handleFileSelect, false);
    
    0 讨论(0)
  • 2020-11-28 03:40

    There is multiple-technology-capable Plupload tool which declares that it can do resizing before upload, but I haven't tried it yet. I have also find a suitable answer in my question about binary image handling javascript libs.

    0 讨论(0)
提交回复
热议问题