I am trying to take a photo in an Android app, convert it to JPEG, then upload it to a web service. So far I got the following:
private static final int CAMERA_REQUEST = 1888;
private void TakePhoto() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CAMERA_REQUEST:
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 90, bos);
byte [] bitmapData = bos.toByteArray();
char [] dataAsChar = new String(bitmapData ).toCharArray();
URL url = new URL("http://www.foo.com/bar);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/octet-stream");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(dataAsChar);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
break;
}
}
The itself seems to work, e.g. doesn’t crash. I get in the Bitmap photo variable. I then compress it using ByteArrayOutputStream and it becomes about 5103 bytes (in the buffer). I then convert it to a char array (so that it can be sent) and the char array becomes 4758 elements. Not sure why that is (probably this line char [] dataAsChar = new String(data).toCharArray();). And of course once the image makes over to the other side it’s corrupted.
What am I missing here?
EDIT. Per suggestion from @digitalJoel, I chucked the OutputStreamWriter and replaced with
OutputStream os = conn.getOutputStream();
os.write(data);
new String(bitmapData ).toCharArray()seems like a really bad idea to me. I don’t think you can expect all the bytes from a JPEG to get shoved into a String without some corruption happening. So, why not just write the bytes to the OutputStream instead of wrapping it in the OutputStreamWriter?