Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Sunday, January 27, 2013

Image POST Client and Sever in Python and C#

From last time, I had told how to encode image into base64 string[1], and how to do POST message to HTTP server[2][3] This post will continue from those posts. First, we will create HTTP POST server in Python. I based on the concept that a message will be encoded using url-encode format in a form of base64 string, and the image string will be sent to a variable named "img". It will decode an image string from that variable.
import SimpleHTTPServer
import SocketServer
import cgi
from base64 import decodestring

PORT = 8000

class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

 def _writeheaders(self):
  self.send_response(200)
  self.send_header('Content-type', 'text/html')
  self.end_headers()

 def do_GET(self):
  filename = 'temp.png'
  f = open(filename, 'rb')
  encode = f.read().encode('base64')
  img = '<img height="200" src="data:image/png;base64,' + encode + '" width="250" />'
  self._writeheaders()
  self.wfile.write("""
  <html><head><title>Simple Server</title></head>
   <body>
    It worked!!!!
 
    %s
   </body>
  </html>"""  % (img))
 def do_POST(self):
  form = cgi.FieldStorage(
   fp=self.rfile,
   headers=self.headers,
   environ={'REQUEST_METHOD':'POST',
      'CONTENT_TYPE':self.headers['Content-Type'],
     })
  encode = form['img'].value
  decode = decodestring(encode)
  output = open('temp.png', 'wb')
  output.write(decode)
  output.close()
  # After posting image has done, it will response GET message to show that image
  self.do_GET()

Handler = ServerHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()
Then, we will create HTTP POST client to upload an image to our HTTP POST server.
Python:
import urllib, urllib2

uri = 'http://localhost:8000'
filename = 'Leafa.jpg'
f = open(filename, 'rb')
encode = f.read().encode('base64')
params = { 'img' : encode }
data = urllib.urlencode(params)

p = urllib2.urlopen(uri, data)
print p.read()
C# WPF:
string fileName = "Leafa.jpg";
StreamResourceInfo sri = null;
Uri uri = new Uri(fileName, UriKind.Relative);
sri = Application.GetResourceStream(uri);

using (var memoryStream = new MemoryStream())
{
    sri.Stream.CopyTo(memoryStream);
    byte[] result = memoryStream.ToArray();
    var base64 = "img=" + HttpUtility.UrlEncode(System.Convert.ToBase64String(result));

    MessageBox.Show(base64);

    using (var wc = new WebClient())
    {
        wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
        wc.UploadStringCompleted += wc_UploadStringCompleted;
        wc.UploadStringAsync(new Uri(url), "POST", base64);
    }
}
The server will response a web page, which the client will show that response as a text format, so, if you want to make sure that your image are already uploaded, just check it the "server.py" directory. You will see the image named "temp.png", which is converted from jpg image in the client side. Moreover, you can use a web browser request to http://localhost:8000 to let GET response show you that uploaded one.

The sample project is uploaded, can download from http://www.mediafire.com/?1okv3lc6nk1jsc7.

Leafa.jpg
References:
  1. Encode an Image into base64 string in C# / Python
  2. Simple HTTP POST Server / Client with Python
  3. HTTP POST data via WebClient and WebRequest

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete