//Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//打开相机方式一
//Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//打开相机方式二
File file=new File(Environment.getExternalStorageDirectory(), "camera.jpg");
//创建图片路径和名称
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));//图片输出位置
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);/*图片质量,范围[0,1]*/
startActivityForResult(intent, 10);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 80);
intent.putExtra("outputY", 80);
intent.putExtra("return-data", true);
startActivityForResult(intent, 11);
//调用录像机功能的代码如下:
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//限制质量
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0.9);
//限制时长
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 5);
//限制大小
intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 1024*1024);
startActivityForResult(intent, 11);
activity_main1.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".TakePhoto">
<LinearLayout
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/btn_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="takePhotos"
android:text="不指定路径拍照:缩略图" />
<Button
android:id="@+id/btn_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="takePhotos"
android:text="指定路径拍照:原图" />
<Button
android:id="@+id/btn_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="takePhotos"
android:text="常用方法拍照:数据库更新" />
LinearLayout>
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/layout"
android:layout_centerInParent="true"
android:scaleType="fitXY" />
RelativeLayout>
TakePhoto.java
package com.example.administrator.myangularjsweb;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by Administrator on 2017/3/14.
*/
public class TakePhoto extends AppCompatActivity {
private ImageView iv;
private Bitmap bitmap;
private Uri uri;
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
iv = ((ImageView) findViewById(R.id.iv));
}
public void takePhotos(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
switch (view.getId()) {
case R.id.btn_1://没有路径:缩略图
startActivityForResult(intent, 1);
break;
case R.id.btn_2://原图
//获取系统下载目录,外部存储download文件夹下
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
//设置图片名称
String name = "IMG" + sdf.format(new Date()) + ".png";
uri = Uri.fromFile(new File(dir, name));
//设置拍摄照片的保存路径
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, 2);
break;
case R.id.btn_3://最常用方式
ContentValues contentValues = new ContentValues();
//设置拍摄照片的名称
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, "IMG" + sdf.format(new Date()) + ".png");
//向保存照片的数据库插入一条数据
Uri uri1 = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri1);
startActivityForResult(intent, 3);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
bitmap = ((Bitmap) data.getExtras().get("data"));
Log.d("google_lenve_fb", "onActivityResult: width:" + bitmap.getWidth() + ";height:" + bitmap.getHeight());
iv.setImageBitmap(bitmap);
} else if (requestCode == 2 && resultCode == RESULT_OK) {
iv.setImageURI(uri);
} else if (requestCode == 3 && resultCode == RESULT_OK) {
//从Images的ContentProvider中查询数据
//1.要查询数据的URI
//2.要查询的字段
//3.查询条件
//4.查询条件中占位符的值
//5.排序字段
Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new
String[]{MediaStore.Images
.Media.DATA}, null, null, MediaStore.Images.Media.DATE_ADDED + " Desc");//Desc前有一个空格
//第一条数据就是刚刚拍摄的照片的信息
if (cursor.moveToFirst()) {
//获得图片存储路径(不同手机会有差异)
String imagePath = cursor.getString(0);
// String path = mCursor.getString(_date);
Log.d("google_lenve_fb", "onActivityResult: imagePath:" + imagePath);
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
iv.setImageBitmap(bitmap);
cursor.close();
}
}
}
}
activity_camera_show.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button_cameraButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="拍照" />
<Button
android:id="@+id/button_photoButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="相册" />
<ImageView
android:id="@+id/imageview_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:src="@mipmap/ic_launcher" />
LinearLayout>
TakePhoto2.java
依赖:
compile 'com.squareup.picasso:picasso:2.5.2'
package com.example.administrator.myangularjsweb;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by Administrator on 2017/3/14.
*/
public class TakePhoto2 extends AppCompatActivity {
private static final String TAG = "TakePhoto2";
private ImageView mImageView;
private Button mButtonCamera;
private Button mButtonPhoto;
private static final int REQUEST_CAMERA = 111;
private static final int REQUEST_ALBUM_OK = 222;
File mTmpFile;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_show);
mImageView = (ImageView) this.findViewById(R.id.imageview_preview);
mButtonCamera = (Button) this.findViewById(R.id.button_cameraButton);
mButtonPhoto = (Button) this.findViewById(R.id.button_photoButton);
//打开Camera
mButtonCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 跳转到系统照相机,隐示意图:指定action,不指定activity
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//对隐式Intent的运行时检查保护,防止系统相机应用被关闭或者不存在相机应用而crash
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// 设置系统相机拍照后的输出路径
// 创建临时文件,使用系统上下文避免内存泄漏
mTmpFile = OtherUtils.createFile(getApplicationContext());
/*输出文件路径和文件名=name:output,value:URI*/
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
startActivityForResult(cameraIntent, REQUEST_CAMERA);
} else {
Toast.makeText(getApplicationContext(), "你的手机竟然没相机!!!!", Toast.LENGTH_SHORT).show();
}
}
});
//获取相册
mButtonPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(albumIntent, REQUEST_ALBUM_OK);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CAMERA://打开相机拍照后
if (mTmpFile != null) {
Log.d(TAG, "onActivityResult: 请求相机: " + mTmpFile.getAbsolutePath());
//打印结果:/storage/emulated/0/1489474548266.jpg
Picasso.with(this)
.load(mTmpFile)
.centerCrop()
.resize(OtherUtils.dip2px(this, 100), OtherUtils.dip2px(this, 100))
.error(R.mipmap.ic_launcher)
.into(mImageView);
}
break;
case REQUEST_ALBUM_OK://打开相册选取图片后
Log.d(TAG, "onActivityResult:相册 " + data.getData().toString());
//打印结果:file:///storage/emulated/0/DCIM/Camera/IMG_20170102_115337_HDR.jpg
// 外界的程序通过ContentResolver接口可以访问ContentProvider提供的数据,
// 在Activity当中通过getContentResolver()可以得到当前应用的 ContentResolver实例
ContentResolver resolver = getContentResolver();
try {
InputStream inputStream = resolver.openInputStream(data.getData());/*获取输入流*/
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);/*流操作*/
mImageView.setImageBitmap(bitmap);
inputStream.close();/*关闭流*/
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
OtherUtils.java
package com.example.administrator.myangularjsweb;
import android.content.Context;
import android.os.Environment;
import java.io.File;
import java.util.Date;
/**
* Created by Administrator on 2017/3/14.
*/
public class OtherUtils {
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/**
* 获取拍照相片存储文件
*
* @param context
* @return
*/
public static File createFile(Context context) {
File file;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String timeStamp = String.valueOf(new Date().getTime());
file = new File(Environment.getExternalStorageDirectory() +
File.separator + timeStamp + ".jpg");
} else {
File cacheDir = context.getCacheDir();
String timeStamp = String.valueOf(new Date().getTime());
file = new File(cacheDir, timeStamp + ".jpg");
}
return file;
}
}
对于某个已知的uri,获取二进制文件读写
// 对于某个已知的uri,获取二进制文件读写
try{
OutputStream file = getContentResolver().openOutputStream(uri);
// ... ... //写处理
file.close();
}catch (Exception e){
Log.e(TAG,e.toString());
}
try{
InputStream in = getContentResolver().openInputStream(uri);
// ... ... //读处理
in.close();
}catch (Exception e){
Log.e(TAG,e.toString());
}
Android Camera 使用小结
Android - 使用Intent来启动Activity
android 多媒体和相机详解五
getContentResolver
Pro Android学习笔记(九):了解Content Provider(下下)
Intent之resolveActivity() 防止APP崩溃
resolveActivity—-对隐式Intent的运行时检查保护
resolveActivity API的使用范例如下:
Intent intent = new Intent(Intent.ACTION_XXX);
ComponentName componentName = intent.resolveActivity(getPackageManager());
if(componentName != null) {
String className = componentName.getClassName();
}
通过PackageManager可以判断Android设备是否有相机!
PackageManager pm = getPackageManager();
// FEATURE_CAMERA - 后置相机
// FEATURE_CAMERA_FRONT - 前置相机
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)
&& !pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) {
Log.i("camera", "non-support");
} else {
Log.i("camera", "support");
}