I am working on an applet that interfaces with a signature pad. The signature pad API has a function that returns a BufferedImage (assume its called API_CALL_TO_RETURN_BUFFERED_IMAGE()). I can encode to jpeg and write this image to file just fine (Using FileOutputStream). However, instead of writing to the local disk, I need to upload the jpeg-encoded image to the server. I can POST data to the server just fine, and I can encode the image just fine; but I am struggling in having the two tasks meet in the middle.
The following is a condensed version of the code (try-catch, function, classes omitted):
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JPEGImageEncode jie = JPEGCodec.createJPEGEncoder(baos);
jpeg.encode(API_CALL_TO_RETURN_BUFFERED_IMAGE()); // assume magic
// baos now contains jpeg data
URLConnection urlc = new URL(some_url).openConnection();
// set up urlc request headers and such
DataOutputStream dos = new DataOutputStream(urlc.getOutputStream());
dos.writeBytes(???); // ??? should be image=[the data in baos above]
// close stuff
Originally, I thought:
String post_data = URLEncoder.encode("image=" + new String(baos.toByteArray()), some_charset);
dos.writeBytes(post_data);
But that clearly distorts the image.
This is what the proper (written locally) image looks like
I can only post one hyperlink, but the distorted image is here: imgur.com/mbmJL.jpg
How do I write a ByteArrayOutputStream to a DataOutputStream?
EDIT/UPDATE:
My solution was to do a mutlipart POST. The reason for setting the Content-Type header as multipart/form-data was, as this link, http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4, says:
multipart/form-data should be used for files, non-ascii values, or binary data
As far as writing a ByteArrayOutputStream to a DataOutputStream, it looks like:
dos.writeBytes(baos.toByteArray());
I am sure that is trivial to full-time Java programmers, but not I!
I did not use the library that was suggested because it offered way more then I needed.