簡體   English   中英

使用python-flask壓縮並上傳圖像

[英]Compress and upload image using python-flask

我正在使用Python-flask應用程序進行圖像處理,但是,當我嘗試通過request.args.get('image'嘗試通過python方法訪問圖像時,圖像壓縮在JavaScript中完成然后上傳正在python flask后端完成'),給出詳述如下

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

它為我工作壓縮和上傳圖像。

 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/JIC/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)

哦,讓我糾正我在你的代碼中發現的一些問題!

首先,您需要使用javascript中的FormData對象 ,以便在這種情況下將字節數據發送到服務器(您的壓縮圖像)。 要做到這一點,我添加了以下代碼:

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"

正如這里所說的get_data方法

這會將來自客戶端的緩沖傳入數據讀入一個字節串。 默認情況下,這是緩存的,但可以通過將緩存設置為False來更改該行為

現在第二個問題是找到如何將該字符串字節文件保存為服務器上的圖像:

仍在尋找如何做到這一點將很快添加它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM