【问题标题】:Compress and upload image using python-flask使用 python-flask 压缩和上传图片
【发布时间】:2018-06-13 20:51:52
【问题描述】:

我正在使用 Python-flask 应用程序进行图像处理,但是,当我尝试通过 request.args.get 以 python 方法访问图像时,图像压缩在 JavaScript 中完成,然后在 python 烧瓶后端完成上传('image'),它给出 None 详细信息如下

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>
我面临的问题是我无法通过 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";

【问题讨论】:

  • 感谢您的编辑和帮助。我没有在 python 中得到我在 ajax 调用中传递的图像参数。我做错了什么?请建议。
  • 在 flask.pocoo.org/docs/0.12/patterns/fileuploads 链接中,我们接受 标签的参数,但在我的情况下,我需要压缩图像对象。我怎样才能在 python 中得到这个?
  • 或者另一方面,我怎样才能将此压缩对象设置为其他对象,以便我可以在 python 中访问它?请建议。
  • 等一下,我有一个建议!您将不得不在您的服务器中保存图像对吗?@VinayakMahajan

标签: javascript python flask image-upload


【解决方案1】:

压缩和上传图像对我有用。

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

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)

【讨论】:

    【解决方案2】:

    好吧, 让我纠正我在您的代码中发现的一些问题!

    首先,在这种情况下,您需要使用 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

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

    仍在寻找方法会尽快添加。

    【讨论】:

    • 好的,非常感谢您的帮助。
    • 是的,但是我无法将其转换为图像格式,所以我开始使用 JIC 库github.com/brunobar79/J-I-C。有了这个,我得到了 python 中的图像对象,但是由于某种原因,我压缩的图像被损坏了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    相关资源
    最近更新 更多