//首先声明一个成员变量 String savePath,用来储存文件路径 /** * 保存照片路径 * @return 返回图片的一个文件 * @throws IOException 抛出一个异常 */ private File createSavePath() throws IOException{ String saveFormat = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + saveFormat + "_"; File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); File image = File.createTempFile(imageFileName,".jpg",storageDir); savePath = image.getAbsolutePath(); //将照片添加到相册中以便其他应用查看 galleryAddPic(); return image; }
/** * 将照片添加到相册中 */ private void galleryAddPic() { Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); File f = new File(savePath); Uri contentUri = Uri.fromFile(f); intent.setData(contentUri); this.sendBroadcast(intent); }
/** * 解码一幅缩放图片,放到imageview中 */ private void setPic() { // 得到imgeView这个控件的尺寸 int targetW = imageView.getWidth(); int targetH = imageView.getHeight(); // 得到这个位图的尺寸 BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(savePath, bmOptions); int photoW = bmOptions.outWidth; int photoH = bmOptions.outHeight; // 确定图片的缩减比例 int scaleFactor = Math.min(photoW/targetW, photoH/targetH); // 解码图像文件到一个位图的大小来填充视图 bmOptions.inJustDecodeBounds = false; bmOptions.inSampleSize = scaleFactor - 1;//这里我用的减1 ,因为在运行过程中程Bitmap too large to be uploaded into a texture (3120x4160, max=4096x4096) 就只能相对减少一个比例 bmOptions.inPurgeable = true; Bitmap bitmap = BitmapFactory.decodeFile(savePath, bmOptions); imageView.setImageBitmap(bitmap); }
最后调用,启动相机拍照
private void startActivity(){ //启动相机并给新照片创建文件对象 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //在调用activity的时候首先调用resolveActivity(),判断调用的activity有没有执行这个的能力 if (intent.resolveActivity(getPackageManager()) != null) { File file = null; try { file = createSavePath(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(),"IO异常错误!",Toast.LENGTH_LONG).show(); } if (file != null){ intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); startActivityForResult(intent,REQUESTCODE); } } }
最后一步,在相机返回的时候用解码的位图显示到imageview中
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //首先判断返回是否成功 if (requestCode == REQUESTCODE && resultCode == RESULTCODE){ //解码图片放到imageview中 setPic(); } }
简单的拍照就完成了。
录像并播放
跳转到录像:
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); if (intent.resolveActivity(getPackageManager()) != null){ startActivityForResult(intent,REQUESTCODE_VIDEO); }
和拍照类似
if (requestCode == REQUESTCODE_VIDEO && resultCode == RESULTCODE){ //得到录制视频的uri Uri uri = data.getData(); imageView.setVisibility(View.GONE); videoView.setVisibility(View.VISIBLE); //将uri设置到videoview中 videoView.setVideoURI(uri); //实例化一个控制 mediaco = new MediaController(TakePicture.this); videoView.setMediaController(mediaco); mediaco.setMediaPlayer(videoView); videoView.requestFocus(); }
在onActivityResult中实现即可。