android 拍照上传照片

openkk 12年前

     废话不多说,直接进入主题,想要在android中实现拍照最简单饿方法就是New 一个 Intent 设置Action为android.media.action.IMAGE_CAPTURE 然后使用startActivityForResult(intent,REQUEST_CODE)方法进入相机。当然还有很多方式可以实现,大家可以在网上查找。但是要注意的是在进入相机前最好判断下sdcard是否可用,代码如下:

                           destoryBimap();     String state = Environment.getExternalStorageState();     if (state.equals(Environment.MEDIA_MOUNTED)) {      intent = new Intent("android.media.action.IMAGE_CAPTURE");      startActivityForResult(intent, REQUEST_CODE);     } else {      Toast.makeText(DefectManagerActivity.this,        R.string.common_msg_nosdcard, Toast.LENGTH_LONG).show();     }
当拍照完成以后需要在onActivityResult(int requestCode, int resultCode, Intent data)方法中获取拍摄的图片,android把拍摄的图片封装到bundle中传递回来,但是根据不同的机器获得相片的方式不太一样,所以会出现某一种方式获取图片为null的想象,解决办法就是做一个判断,当一种方式不能获取,就是用另一种方式,下面是分别获取相片的两种方式:
                           Uri uri = data.getData();     if (uri != null) {      photo = BitmapFactory.decodeFile(uri.getPath());     }     if (photo == null) {      Bundle bundle = data.getExtras();      if (bundle != null) {       photo = (Bitmap) bundle.get("data");      } else {       Toast.makeText(DefectManagerActivity.this,         getString(R.string.common_msg_get_photo_failure),         Toast.LENGTH_LONG).show();       return;      }     }

第一种方式是用方法中传回来的intent调用getData();方法获取数据的Uri,然后再根据uri获取数据的路径,然后根据路径封装成一个bitmap就行了.

第二种方式也是用法中传回来的intent对象但是不再是调用getData();方法而是调用getExtras();方法获取intent里面所有参数的一个对象集合bundle,然后是用bundle对象得到键为data的值也就是一个bitmap对象.

通过上面两种方式就能获取相片的bitmap对象,然后就可以在程序中是用,如果你想把相片保存到自己指定的目录可以是用如下步骤即可:

首先bitmap有个一compress(Bitmap.CompressFormat.JPEG, 100, baos)方法,这个方法有三个参数,第一个是指定将要保存的图片的格式,第二个是图片保存的质量,值是0-100,比如像PNG格式的图片这个参数你可以随便设置,因为PNG是无损的格式。第三个参数是你一个缓冲输出流ByteArrayOutputStream();,这个方法的作用就是把 bitmap的图片转换成jpge的格式放入输出流中,然后大家应该明白怎么操作了吧,下面是实例代码:

                  String pictureDir = "";    FileOutputStream fos = null;    BufferedOutputStream bos = null;    ByteArrayOutputStream baos = null;    try {     baos = new ByteArrayOutputStream();     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);     byte[] byteArray = baos.toByteArray();     String saveDir = Environment.getExternalStorageDirectory()       + "/temple";     File dir = new File(saveDir);     if (!dir.exists()) {      dir.mkdir();     }     File file = new File(saveDir, "temp.jpg");     file.delete();     if (!file.exists()) {      file.createNewFile();     }     fos = new FileOutputStream(file);     bos = new BufferedOutputStream(fos);     bos.write(byteArray);     pictureDir = file.getPath();    } catch (Exception e) {     e.printStackTrace();    } finally {     if (baos != null) {      try {       baos.close();      } catch (Exception e) {       e.printStackTrace();      }     }     if (bos != null) {      try {       bos.close();      } catch (Exception e) {       e.printStackTrace();      }     }     if (fos != null) {      try {       fos.close();      } catch (Exception e) {       e.printStackTrace();      }     }    }
然后就是实现图片的上传功能,我这里是是用的apache的HttpClient里面的MultipartEntity实现文件上传具体代码如下:
/**    * 提交参数里有文件的数据    *     * @param url    *            服务器地址    * @param param    *            参数    * @return 服务器返回结果    * @throws Exception    */   public static String uploadSubmit(String url, Map<String, String> param,     File file) throws Exception {    HttpPost post = new HttpPost(url);      MultipartEntity entity = new MultipartEntity();    if (param != null && !param.isEmpty()) {     for (Map.Entry<String, String> entry : param.entrySet()) {      entity.addPart(entry.getKey(), new StringBody(entry.getValue()));     }    }    // 添加文件参数    if (file != null && file.exists()) {     entity.addPart("file", new FileBody(file));    }    post.setEntity(entity);    HttpResponse response = httpClient.execute(post);    int stateCode = response.getStatusLine().getStatusCode();    StringBuffer sb = new StringBuffer();    if (stateCode == HttpStatus.SC_OK) {     HttpEntity result = response.getEntity();     if (result != null) {      InputStream is = result.getContent();      BufferedReader br = new BufferedReader(        new InputStreamReader(is));      String tempLine;      while ((tempLine = br.readLine()) != null) {       sb.append(tempLine);      }     }    }    post.abort();    return sb.toString();   }
这里就基本上对图片上传就差不多了,但是还有一个问题就是图片上传完以后bitmap还在内存中,而且大家都知道如果,高清的图片比较大,而手机内存本来就有限,如果不进行处理很容易报内存溢出,所以我们应该把处理完的bitmap从内存中释放掉,这时候就需要调用bitmap的recycle();方法,调用这个方法的时候需要注意不能太早也不能太晚,不然会报异常,一般可以放在下一张图片生成前或者没有任何view引用要销毁的图片的时候下面是实例代码:
/**    * 销毁图片文件    */   private void destoryBimap() {    if (photo != null && !photo.isRecycled()) {     photo.recycle();     photo = null;    }   }
转自:http://blog.csdn.net/yaoyeyzq/article/details/7254679