因为临时须要作个简单的Android程序,其中涉及调用系统拍照并保存照片。以前没有任何Java和Android经验,coding中遇到很多问题,特记录以供参考。java
Google一下能找到很多现成的调用系统拍照的代码,可弄了一天也没成功。测试手机为Defy,系统是Android4.0/MIUI-1.11-9。先附上网上搜所的代码,后说明遇到的问题:android
1.响应按钮点击事件,调用系统拍照,其中RESULT_CAPTURE_IMAGE为自定义拍照标志。ide
public void onClick(View v) { startActivityForResult(new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE,RESULT_CAPTURE_IMAGE); }
2.Override onActivityResult(int requestCode, int resultCode, Intent data)方法,在此方法中保存图片。其中imagePath在此类中已定义,操做sdcard权限在清单文件中已添加,判断sdcard是否存在以及指定文件目录是否存在在此以前都已作处理。测试
public void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == RESULT_CAPTURE_IMAGE) { if(resultCode == RESULT_OK) { File file = new File(imagePath); Bitmap bitmap = (Bitmap)data.getExtras().get("data"); try { BufferOutputStream bos = new BufferOutputStream(new FileOutputStream(file)); //采用压缩转档方法 bitmap.compress(Bitmap.CompressFormat.JPEG,80,bos); bos.flush(); bos.close(); }catch(Exception e) { e.printStackTrace(); } } } }
用以上代码碰到的问题:this
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); Uri uri = Uri.fromFile(new File(imagePath)); intent.putExtra(MediaStore.EXTRA_OUTPUT,uri); startActivityForResult(intent,RESULT_CAPTURE_IMAGE);
将按钮onClick方法中采用以上代码,调用系统拍照并肯定以后,没法返回程序Activity。继续Google,终于找到解决办法,代码以下(在 if(resultCode == RESULT_OK)里面)
Bitmap bitmap = null; File file = new File(imagePath); bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); if(bitmap == null) { Toast.makeText(this,R.string.image_save_error,Toast.LENGTH_LONG).show(); } try { BufferOutputStream bos = new BufferOutputStream(new FileOutputStream(file)); bitmap.compress(Bitmap.CompressFormat.JPEG,80,bos); bos.flush(); bos.close(); }catch(FileNotFoundException e) { e.printStackTrace(); }catch(IOException e) { e.printStackTrace(); } super.onActivityResult(requestCode,resultCode,data);
从新编译后, 在机器上测试经过。其中主要参考连接为 android调用系统相机拍照 获取缘由 以及 android调用系统相机实现拍照功能;其中获取缘由一文中的代码spa
Uri u = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), null, null));
进过跟踪发现图片路径解析错误,最后直接使用了.net
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
来获取bitmap值。
第一次写android程序,对整个开发环境,开发语言以及Android API很不熟悉,花费了很多时间。以上文字感受很是凌乱,代码也只在一款机器上通过测试,但愿能给本身和别人有所帮助。code