手机拍照并压缩图片

 //拍照上传图片临时路径
 private String saveDir = Environment.getExternalStorageDirectory()
   .getPath() + "/cheyouxin/";
 private File file;
 private final int PAIZHAO=1;
 private String photoName=null;//图片名

 

/**拍照方法**/
 public void photo() {
  String state = Environment.getExternalStorageState();//判断是否有sd卡
  File savePath = new File(saveDir);
  if (!savePath.exists()) {
   savePath.mkdirs();
  }
  if (state.equals(Environment.MEDIA_MOUNTED)) {
   photoName = new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
   file = new File(saveDir,photoName);
   file.delete();
   if (!file.exists()) {
    try {
     file.createNewFile();
    } catch (IOException e) {
     e.printStackTrace();
     toast("照片创建失败!");
     return;
    }
   }
   Intent intent = new Intent(
     "android.media.action.IMAGE_CAPTURE");//调用系统拍照
   intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));//拍照文件存在那个文件
   startActivityForResult(intent,PAIZHAO);
  } else {
   toast("sd卡内存不足!");
  }
 }

 

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  switch (requestCode) {
   case PAIZHAO:
    if (file != null && file.exists()) {
     ByteArrayOutputStream baos=new ByteArrayOutputStream();
     BitmapFactory.Options opt=new BitmapFactory.Options();
     opt.inJustDecodeBounds=true;//打开空文件获取分辨率
     Bitmap bitmap=BitmapFactory.decodeFile(file.getPath(), opt);
     int bitWidth = opt.outWidth;
     int bitHeight = opt.outHeight;
     int be=1;
     if(bitWidth>200||bitHeight>200){
      if (bitWidth < bitHeight) {
       // 高度大于宽度
       be = bitHeight/200;
      } else {
       // 宽度大于高度
       be = bitWidth/200;
      }
     }
     opt.inJustDecodeBounds=false;//打开图片
     opt.inSampleSize=be;//压缩比例
      try { 
       bitmap=BitmapFactory.decodeFile(file.getPath(),opt);
       bitmap.compress(CompressFormat.JPEG, 80, baos);//缩放80%
       } catch (OutOfMemoryError e) { 
       opt.inSampleSize = be + 2;  //异常加大缩放比例
       bitmap=BitmapFactory.decodeFile(file.getPath(),opt);
       bitmap.compress(CompressFormat.JPEG, 80, baos);
     }  
     
     takePhoto = new ImageItem();
     takePhoto.setBitmap(bitmap);
     takePhoto.setImagePath(file.getPath());
     Bimp.selectBitmap.add(takePhoto);
    }
    break;
 
   default:
    break;
  }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值