使用python-flask压缩并上传图像

时间:2018-01-04 06:39:30

标签: javascript python flask image-upload

我正在使用Python-flask应用程序进行图像处理,但是,当我尝试通过request.args.get尝试通过python方法访问图像时,图像压缩是在JavaScript中完成的,然后上传正在python flask后端完成(' image'),其提供详情如下



var img = $('#img-upload')[0];
    function readURL(input) {
      if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function(e) {
          $('#img-upload').attr('src', e.target.result);
          img.onload = function() {
              alert("Image is loaded");
              var MAX_WIDTH = 100;
              var MAX_HEIGHT = 100;
              var width = img.width;
              var height = img.height;

              if (width > height) {
                if (width > MAX_WIDTH) {
                  height *= MAX_WIDTH / width;
                  width = MAX_WIDTH;
                }
              } else {
                if (height > MAX_HEIGHT) {
                  width *= MAX_HEIGHT / height;
                  height = MAX_HEIGHT;
                }
              }

              var canvas = document.createElement("canvas");
              canvas.width = width;
              canvas.height = height;
              canvas.getContext("2d").drawImage(this, 0, 0, width, height);
              var newImageData = canvas.toDataURL('image/png', 30/100);
              var result_image_obj = new Image();
              result_image_obj.src = newImageData;
              console.log(result_image_obj.src);
              console.log("Starting Upload...");

              if (result_image_obj.src == "") {
                  alert("You must load an image and compress it first!");
                  return false;
              }
              var callback= function(response){
                  console.log("image uploaded successfully! :)");
                  console.log(response);          
              }
              $.ajax({
                  url:"/users/api/v1/uploadimage",
                  type:'POST',
                  data:{'image':result_image_obj},
                  cache:false,
                  processData:false,
                  contentType:false,
                  error:function(){
                      console.log("upload error")
                  },
                  success:function(data){
                      console.log(data)
                      console.log("upload success")
                  }
              })
              console.log("Completed Upload...");
          }
        }
        reader.readAsDataURL(input.files[0]);
      }
    }

    $("#imgInp").change(function(){
        readURL(this);
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" action="/updateuser" method="POST" enctype="multipart/form-data">
        <input type='file' id="imgInp"/>
        <img id="img-upload" name="img-upload" src="#"/>
</form>
&#13;
&#13;
&#13; 我面临的问题是我无法通过request.args.get在python烧瓶中获取图像,我做错了什么?请建议。 python代码如下

@app.route('/users/api/v1/uploadimage',methods=['GET','POST'])
def uploadimage():
    print "In uploadimage()"
    try:
        file = request.args.get('image')
        print "Filename",file
    except Exception as e:
        print str(e)
        return "True";

2 个答案:

答案 0 :(得分:2)

  

它为我工作压缩和上传图像。

&#13;
&#13;
function readFile(evt) {
	    var file = evt.target.files[0];
	    var reader = new FileReader();
	    output_format = "jpg";
	    reader.onload = function(event) {
	        var i = document.getElementById("source_image");
	            i.src = event.target.result;
	            i.onload = function(){
	                image_width=$(i).width(),
	                image_height=$(i).height();

	                if(image_width > image_height){
	                    i.style.width="320px";
	                }else{
	                    i.style.height="300px";
	                }
	                i.style.display = "block";
	                console.log("Image loaded");
	            }
	    };

	    console.log("Filename:" + file.name);
	    console.log("Filesize:" + (parseInt(file.size) / 1024) + " Kb");
	    console.log("Type:" + file.type);
	    reader.readAsDataURL(file);

	    return false;
	}
 
 	$( "#upload" ).click(function() {
        var source_image = document.getElementById('source_image');
        if (source_image.src == "") {
            alert("You must load an image first!");
            return false;
        }

        var quality = 30;
       	
        console.log("process start...");
        var time_start = new Date().getTime();
        output_format = "jpg";
        console.log("process start compress ...");
	    source_image.src = jic.compress(source_image,quality,output_format).src;
	    console.log('Compressed in: ' + new Date().getTime() - time_start + 'ms');

	    var successCallback= function(response){
            console.log("image uploaded successfully! :)");
            console.log(response);       
        }

        var errorCallback= function(response){
            console.log("image Filed to upload! :)");
            console.log(response); 
        }
    	
    	var time_start = new Date().getTime();
    	console.log("process start upload ...");
    	jic.upload(source_image, '/uploadimage', 'file', 'new.jpg',successCallback,errorCallback);
    	console.log('uploaded in: ' + new Date().getTime() - time_start + 'ms');
    	
    });

document.getElementById('fileinput').addEventListener('change', readFile, false);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="upload_form" action="/updateuser" method="POST" enctype="multipart/form-data">
		<label for="file">Choose file</label>
		<input type="file" id="fileinput" />
		<img id="source_image">
		<input type="button" id="upload" value="uploadimage">
</form>
<script src="https://github.com/brunobar79/J-I-C/blob/master/src/JIC.js"></script>
&#13;
&#13;
&#13;

  

Python代码

def uploadimage():
    print "In uploadimage() trying to upload"
    try:
        file = request.files['file']
        print "File",file
        print "Name",file.filename
    except Exception as e:
        print "Failed",str(e)

答案 1 :(得分:1)

奥基, 让我纠正一下我在你的代码中发现的一些问题!

首先,您需要使用javascript中的FormData object,以便在这种情况下将字节数据发送到服务器(您的压缩图像)。 要做到这一点,我添加了以下代码:

console.log("Starting Upload...");
var formData = new FormData();
formData.append("fileToUpload", result_image_obj.src);

现在您可以轻松地通过ajax发送它:

$.ajax({
                  url:"/users/api/v1/uploadimage",
                  type:'POST',
                  data:formData,
                  processData: false, // important
                  contentType: false, // important
                  enctype: 'multipart/form-data',
                  error:function(){
                      console.log("upload error")
                  },
                  success:function(data){
                      console.log(data)
                      console.log("upload success")
                  }
              })

注意您必须将formData对象作为数据的参数发送到ajax并使用enctype:'multipart / form-data'。

现在在您的烧瓶服务器中使用以下代码:

@app.route('/users/api/v1/uploadimage', methods=['GET', 'POST'])
def uploadimage():
    """
    this will try to upload an image
    """
    print "In uploadimage()"
    try:
        a_file = request.get_data(cache=False, as_text=False, parse_form_data=False)
        print "Filename", a_file
    except Exception as exce:
        print str(exce)
        return "True"
    return "oke"

here所述 get_data方法

  

将来自客户端的缓冲传入数据读入一个   字节字符串。默认情况下,这是缓存的,但可以更改该行为   通过将缓存设置为False

现在第二个问题是找到如何将该字符串字节文件保存为服务器上的图像:

仍在寻找如何做到很快就会添加它。