Decode image from HTTP POST request in python

744 views Asked by At

I am sending an image from my HTML-JS frontend to my Python backend. Below is my JS code:

var formData = new FormData();
formData.append("a", file);

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
    if(this.readyState === 4) {
        log(this.responseText);
    }
});

xhr.open("POST", "http://localhost:8088");

xhr.send(formData);

In my backend I am using BaseHTTPServer to receive this image

self.send_response(200)
self.send_header('Access-Control-Allow-Origin', 'http://localhost:8887')
self.send_header("Access-Control-Allow-Credentials", "true")
self.end_headers()
form = cgi.FieldStorage(
        fp=self.rfile,
        headers=self.headers,
        environ={"REQUEST_METHOD": "POST",
                 "CONTENT_TYPE": self.headers['Content-Type']})
image = form.getvalue("a")
bytes_array = []
for i in range(90000):
    try:
        bytes_array.append(image[i])
    except:
        print(i)
        break
print(bytes_array)

The issue I am facing is that parts of my image variable looks like:

<?xpacket begin=\'\xef\xbb\xbf\' id=\'W5M0MpCehiHzreSzNTczkc9d\'?>\r\n<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="uuid:faf5bdd5-ba3d-11da-ad31-d33d75182f1b" xmlns:dc="http://purl.org/dc/elements/1.1/"/><rdf:Description rdf:about="uuid:faf5bdd5-ba3d-11da-ad31-d33d75182f1b" xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:creator><rdf:Seq xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:li>Bankar, Pranit</rdf:li></rdf:Seq>\r\n\t\t\t</dc:creator></rdf:Description></rdf:RDF></x:xmpmeta>\r\n   

and

<?xpacket end=\'w\'?>

This creates garbage values in my bytes_array.

What would be a proper way to send an image file so that I can extract the pixel values?

1

There are 1 answers

0
Pranit Bankar On

I modified my JS file in the below manner:

let b64_data;

function handleFileSelectTest(event){
  //Change event for image file upload

    img = document.getElementById('img');
    file = event.target.files[0];
    img.src = URL.createObjectURL(file);
    img.onload = function(){
        var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');
        canvas.height = img.naturalHeight;
        canvas.width = img.naturalWidth;
        ctx.drawImage(img, 0, 0);

        var uri = canvas.toDataURL('image/png'),
        b64_data1 = uri.replace(/^data:image.+;base64,/, '');
        b64_data = b64_data1;
    }
}

and

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
    if(this.readyState === 4) {
        log(this.responseText);
    }
});
xhr.open("POST", "http://localhost:8088");
//console.log(b64_data);
xhr.send(b64_data);

I also modified my python code as:

self.send_response(200)
self.send_header('Access-Control-Allow-Origin', 'http://localhost:8887')
self.send_header("Access-Control-Allow-Credentials", "true")
self.end_headers()
content_len = int(self.headers.get('Content-Length'))
post_body = self.rfile.read(content_len)

print(post_body)
data = base64.b64decode(post_body)
with open("imageToSave1.png", "wb") as fh:
    fh.write(base64.decodebytes(post_body))
ans="a b c"
self.wfile.write(ans.encode())