我正在尝试在 Android 应用程序中拍照,将其转换为 JPEG,然后将其上传到网络服务。到目前为止,我得到了以下信息:
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;
}
}
它本身似乎工作,例如不会崩溃。我进入 Bitmapphoto
变量。然后我使用 ByteArrayOutputStream 压缩它,它变成大约 5103 字节(在缓冲区中)。然后我将其转换为 char 数组(以便可以发送),char 数组变为 4758 个元素。不知道为什么会这样(可能是这条线char [] dataAsChar = new String(data).toCharArray();
)。当然,一旦图像转移到另一边,它就会损坏。
我在这里想念什么?
编辑。根据@digitalJoel 的建议,我放弃了 OutputStreamWriter 并替换为
OutputStream os = conn.getOutputStream();
os.write(data);