android 拍照上传照片

废话不多说,直接进入主题,想要在android中实现拍照最简单饿方法就是New 一个 Intent 设置Action为android.media.action.IMAGE_CAPTURE 然后使用startActivityForResult(intent,REQUEST_CODE)方法进入相机。当然还有很多方式可以实现,大家可以在网上查找。但是要注意的是在进入相机前最好判断下sdcard是否可用,代码如下:
  1.                         destoryBimap(); 
  2. String state = Environment.getExternalStorageState(); 
  3. if (state.equals(Environment.MEDIA_MOUNTED)) { 
  4.     intent = new Intent("android.media.action.IMAGE_CAPTURE"); 
  5.     startActivityForResult(intent, REQUEST_CODE); 
  6. } else
  7.     Toast.makeText(DefectManagerActivity.this
  8.             R.string.common_msg_nosdcard, Toast.LENGTH_LONG).show(); 
                           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的想象,解决办法就是做一个判断,当一种方式不能获取,就是用另一种方式,下面是分别获取相片的两种方式:

  1.                         Uri uri = data.getData(); 
  2. if (uri != null) { 
  3.     photo = BitmapFactory.decodeFile(uri.getPath()); 
  4. if (photo == null) { 
  5.     Bundle bundle = data.getExtras(); 
  6.     if (bundle != null) { 
  7.         photo = (Bitmap) bundle.get("data"); 
  8.     } else
  9.         Toast.makeText(DefectManagerActivity.this
  10.                 getString(R.string.common_msg_get_photo_failure), 
  11.                 Toast.LENGTH_LONG).show(); 
  12.         return
  13.     } 
                           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的格式放入输出流中,然后大家应该明白怎么操作了吧,下面是实例代码:

  1.                 String pictureDir = ""
  2. FileOutputStream fos = null
  3. BufferedOutputStream bos = null
  4. ByteArrayOutputStream baos = null
  5. try
  6.     baos = new ByteArrayOutputStream(); 
  7.     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
  8.     byte[] byteArray = baos.toByteArray(); 
  9.     String saveDir = Environment.getExternalStorageDirectory() 
  10.             + "/temple"
  11.     File dir = new File(saveDir); 
  12.     if (!dir.exists()) { 
  13.         dir.mkdir(); 
  14.     } 
  15.     File file = new File(saveDir, "temp.jpg"); 
  16.     file.delete(); 
  17.     if (!file.exists()) { 
  18.         file.createNewFile(); 
  19.     } 
  20.     fos = new FileOutputStream(file); 
  21.     bos = new BufferedOutputStream(fos); 
  22.     bos.write(byteArray); 
  23.     pictureDir = file.getPath(); 
  24. } catch (Exception e) { 
  25.     e.printStackTrace(); 
  26. } finally
  27.     if (baos != null) { 
  28.         try
  29.             baos.close(); 
  30.         } catch (Exception e) { 
  31.             e.printStackTrace(); 
  32.         } 
  33.     } 
  34.     if (bos != null) { 
  35.         try
  36.             bos.close(); 
  37.         } catch (Exception e) { 
  38.             e.printStackTrace(); 
  39.         } 
  40.     } 
  41.     if (fos != null) { 
  42.         try
  43.             fos.close(); 
  44.         } catch (Exception e) { 
  45.             e.printStackTrace(); 
  46.         } 
  47.     } 
                  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实现文件上传具体代码如下:

  1. /**
  2.      * 提交参数里有文件的数据
  3.      *
  4.      * @param url
  5.      *            服务器地址
  6.      * @param param
  7.      *            参数
  8.      * @return 服务器返回结果
  9.      * @throws Exception
  10.      */ 
  11.     public static String uploadSubmit(String url, Map<String, String> param, 
  12.             File file) throws Exception { 
  13.         HttpPost post = new HttpPost(url); 
  14.  
  15.         MultipartEntity entity = new MultipartEntity(); 
  16.         if (param != null && !param.isEmpty()) { 
  17.             for (Map.Entry<String, String> entry : param.entrySet()) { 
  18.                 entity.addPart(entry.getKey(), new StringBody(entry.getValue())); 
  19.             } 
  20.         } 
  21.         // 添加文件参数 
  22.         if (file != null && file.exists()) { 
  23.             entity.addPart("file", new FileBody(file)); 
  24.         } 
  25.         post.setEntity(entity); 
  26.         HttpResponse response = httpClient.execute(post); 
  27.         int stateCode = response.getStatusLine().getStatusCode(); 
  28.         StringBuffer sb = new StringBuffer(); 
  29.         if (stateCode == HttpStatus.SC_OK) { 
  30.             HttpEntity result = response.getEntity(); 
  31.             if (result != null) { 
  32.                 InputStream is = result.getContent(); 
  33.                 BufferedReader br = new BufferedReader( 
  34.                         new InputStreamReader(is)); 
  35.                 String tempLine; 
  36.                 while ((tempLine = br.readLine()) != null) { 
  37.                     sb.append(tempLine); 
  38.                 } 
  39.             } 
  40.         } 
  41.         post.abort(); 
  42.         return sb.toString(); 
  43.     } 
/**
	 * 提交参数里有文件的数据
	 * 
	 * @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引用要销毁的图片的时候下面是实例代码:

  1. /**
  2.      * 销毁图片文件
  3.      */ 
  4.     private void destoryBimap() { 
  5.         if (photo != null && !photo.isRecycled()) { 
  6.             photo.recycle(); 
  7.             photo = null
  8.         } 
  9.     } 
/**
	 * 销毁图片文件
	 */
	private void destoryBimap() {
		if (photo != null && !photo.isRecycled()) {
			photo.recycle();
			photo = null;
		}
	}


好了,这里就讲完了,如果大家还有什么更好的方法,大家可以多交流交流。

 

转自:http://blog.csdn.net/yaoyeyzq/article/details/7254679

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值