获取系统的相机功能拍照这个不难,但是需要注意的是,拍照返回后的照片如果没有指定存储的路径,那么系统将自动保存到sd卡中,得到的是拍完照的缩略图,会失帧,显示有些模糊,所以在调用系统相机拍完照后我们要指定一个路径,将它存起来,需要的时候再去拿,调用相册这里当时需要的是相册的多选,但是系统相册只能单选,所以自定义了一个相册,是直接startActivity的,我们来看看获取相册和系统相机的Intent是怎么写的。
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("添加颜色");
String[] items = {"从相册选取", "拍照"};
builder.setNegativeButton("取消", null);
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case CHOOSE_PICTURE:// 选择本地照片
Intent intent = new Intent(SampleSendActivity.this,SampleCameraActivity.class);
startActivityForResult(intent, ACTION_IMAGE_PICTURE);
break;
case TAKE_PICTURE:// 拍照
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
/**
* 每次拍照新建一个照片文件
*/
String name = new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
File file = new File("/sdcard/myImage/");
file.mkdirs();// 创建文件夹
mFilePath = "/sdcard/myImage/"+name;
// 加载路径
Uri uri = Uri.fromFile(new File(mFilePath));
// 指定存储路径,这样就可以保存原图了
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
// 拍照返回图片
startActivityForResult(intent, ACTION_IMAGE_CAMEREA);
break;
}
}
});
builder.create().show();
现在我们来看看调用系统相册后去获取指定的file,直接通过路径显示在imageview中
if (requestCode == ACTION_IMAGE_CAMEREA && resultCode == Activity.RESULT_OK) {
String storageState = Environment.getExternalStorageState();
if (!storageState.equals(Environment.MEDIA_MOUNTED)) {
return;
}
// /sdcard
mFilePath = "/storage/emulated/0" + mFilePath.substring(7);
BitmapUtil.loadUriImage(SampleSendActivity.this, mFilePath, tagHolder.iv_pinkaddpig);
//这里的bitmaputil是我自己写的,就是通过路径加载到imageview中,可以忽略
}
再来看看自定义多选相册的实现
public class SampleCameraActivity extends Activity implements OnImageDirSelected {
private ProgressDialog mProgressDialog;
/**
* 存储文件夹中的图片数量
*/
private int mPicsSize;
/**
* 图片数量最多的文件夹
*/
private File mImgDir;
/**
* 所有的图片
*/
private List<String> mImgs;
private GridView mGirdView;
private MyAdapter mAdapter;
/**
* 临时的辅助类,用于防止同一个文件夹的多次扫描
*/
private HashSet<String> mDirPaths = new HashSet<String>();
/**
* 扫描拿到所有的图片文件夹
*/
private List<ImageFloder> mImageFloders = new ArrayList<ImageFloder>();
private RelativeLayout mBottomLy;
private TextView mChooseDir;
private TextView mImageCount;
int totalCount = 0;
private int mScreenHeight;
private ListImageDirPopupWindow mListImageDirPopupWindow;
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
mProgressDialog.dismiss();
// 为View绑定数据
data2View();
// 初始化展示文件夹的popupWindw
initListDirPopupWindw();
}
};
private TextView tv_samplecamera_confirm;
private TextView tv_return;
/**
* 为View绑定数据
*/
private void data2View() {
if (mImgDir == null) {
Toast.makeText(getApplicationContext(), "擦,一张图片没扫描到",
Toast.LENGTH_SHORT).show();
return;
}
mImgs = Arrays.asList(mImgDir.list());
/**
* 可以看到文件夹的路径和图片的路径分开保存,极大的减少了内存的消耗;
*/
mAdapter = new MyAdapter(getApplicationContext(), mImgs,
R.layout.view_cameragrid_item, mImgDir.getAbsolutePath());
mAdapter.setIamgeNull();
mGirdView.setAdapter(mAdapter);
mImageCount.setText(totalCount + "张");
};
/**
* 初始化展示文件夹的popupWindw
*/
private void initListDirPopupWindw() {
mListImageDirPopupWindow = new ListImageDirPopupWindow(
(int) LayoutParams.MATCH_PARENT, (int) (mScreenHeight * 0.7),
mImageFloders, LayoutInflater.from(getApplicationContext())
.inflate(R.layout.view_cameralist_dir, null));
mListImageDirPopupWindow.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {
// 设置背景颜色变暗
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 1.0f;
getWindow().setAttributes(lp);
}
});
// 设置选择文件夹的回调
mListImageDirPopupWindow.setOnImageDirSelected(this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_camera);
DisplayMetrics outMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
mScreenHeight = outMetrics.heightPixels;
getActionBar().hide();
initView();
getImages();
initEvent();
}
/**
* 利用ContentProvider扫描手机中的图片,此方法在运行在子线程中 完成图片的扫描,最终获得jpg最多的那个文件夹
*/
private void getImages() {
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
return;
}
// 显示进度条
mProgressDialog = ProgressDialog.show(this, null, "正在加载...");
new Thread(new Runnable() {
@Override
public void run() {
String firstImage = null;
Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver mContentResolver = SampleCameraActivity.this
.getContentResolver();
// 只查询jpeg和png的图片
Cursor mCursor = mContentResolver.query(mImageUri, null,
MediaStore.Images.Media.MIME_TYPE + "=? or "
+ MediaStore.Images.Media.MIME_TYPE + "=?",
new String[]{"image/jpeg", "image/png"},
MediaStore.Images.Media.DATE_MODIFIED);
Log.e("TAG", mCursor.getCount() + "");
while (mCursor.moveToNext()) {
// 获取图片的路径
String path = mCursor.getString(mCursor
.getColumnIndex(MediaStore.Images.Media.DATA));
Log.e("TAG", path);
// 拿到第一张图片的路径
if (firstImage == null)
firstImage = path;
// 获取该图片的父路径名
File parentFile = new File(path).getParentFile();
if (parentFile == null)
continue;
String dirPath = parentFile.getAbsolutePath();
ImageFloder imageFloder = null;
// 利用一个HashSet防止多次扫描同一个文件夹(不加这个判断,图片多起来还是相当恐怖的~~)
if (mDirPaths.contains(dirPath)) {
continue;
} else {
mDirPaths.add(dirPath);
// 初始化imageFloder
imageFloder = new ImageFloder();
imageFloder.setDir(dirPath);
imageFloder.setFirstImagePath(path);
}
int picSize = 0;
try{
picSize = parentFile.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (filename.endsWith(".jpg")
|| filename.endsWith(".png")
|| filename.endsWith(".jpeg"))
return true;
return false;
}
}).length;
}catch (Exception e){
e.printStackTrace();
}
totalCount += picSize;
imageFloder.setCount(picSize);
mImageFloders.add(imageFloder);
if (picSize > mPicsSize) {
mPicsSize = picSize;
mImgDir = parentFile;
}
}
mCursor.close();
// 扫描完成,辅助的HashSet也就可以释放内存了
mDirPaths = null;
// 通知Handler扫描图片完成
mHandler.sendEmptyMessage(0x110);
}
}).start();
}
/**
* 初始化View
*/
private void initView() {
mGirdView = (GridView) findViewById(R.id.id_gridView);
tv_samplecamera_confirm = (TextView) findViewById(R.id.tv_samplecamera_confirm);
mChooseDir = (TextView) findViewById(R.id.id_choose_dir);
tv_return = (TextView) findViewById(R.id.tv_return_samplecamera);
mImageCount = (TextView) findViewById(R.id.id_total_count);
mBottomLy = (RelativeLayout) findViewById(R.id.id_bottom_ly);
}
private void initEvent() {
tv_samplecamera_confirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ArrayList<String> imageList = mAdapter.getImageList();
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putStringArrayList("images", imageList);
intent.putExtras(bundle);
setResult(11, intent);
finish();
}
});
tv_return.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
/**
* 为底部的布局设置点击事件,弹出popupWindow
*/
mBottomLy.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mListImageDirPopupWindow
.setAnimationStyle(R.style.anim_popup_dir);
mListImageDirPopupWindow.showAsDropDown(mBottomLy, 0, 0);
// 设置背景颜色变暗
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = .3f;
getWindow().setAttributes(lp);
}
});
}
public void selected(ImageFloder floder) {
mImgDir = new File(floder.getDir());
mImgs = Arrays.asList(mImgDir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (filename.endsWith(".jpg") || filename.endsWith(".png")
|| filename.endsWith(".jpeg"))
return true;
return false;
}
}));
/**
* 可以看到文件夹的路径和图片的路径分开保存,极大的减少了内存的消耗;
*/
mAdapter = new MyAdapter(getApplicationContext(), mImgs,
R.layout.view_cameragrid_item, mImgDir.getAbsolutePath());
mGirdView.setAdapter(mAdapter);
mImageCount.setText(floder.getCount() + "张");
mChooseDir.setText(floder.getName());
mListImageDirPopupWindow.dismiss();
}
}
来看看调用后的效果
相册调用后返回的是包含相片的本地路径字符串
ArrayList<String> imageArrayList = bundle.getStringArrayList("images");