从本机选择图片上传或拍照上传:
先弹出选择框,选择“从相册选取图片”,“拍照”,“取消”
MainActivity.java
public class EmployeesAddActivity extends BaseActivity implements View.OnClickListener {
private static final String TAG = "EmployeesAddActivity";
private Context mContext;
……
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_upload:
pickFile(2001);
break;
}
}
// 打开系统的文件选择器
public void pickFile(int requestCode) {
FileLoadUtils.showPhotoDialog((Activity) mContext,requestCode);
}
//记录选择图片或拍照的数量
int count = 0;
//保存图片路径
private List pathList = new ArrayList<>();
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2001 && resultCode == RESULT_OK) {
Log.e(TAG,"data="+data.getData()+","+data.getDataString());
if (data == null) {
return;
}
if (count == 2) {
Toast.makeText(mContext,"最多上传2张照片",Toast.LENGTH_SHORT).show();
return;
}
String str = FileLoadUtils.handleImageOnKitKat(mContext,data);
Log.e(TAG,"str="+str);
str = FileLoadUtils.saveBitmap(mContext,FileLoadUtils.getimage(str));
pathList.add(str);
ImgGridAdapter imageAdapter = new ImgGridAdapter(mContext, pathList);
rv_health.setAdapter(imageAdapter);
count ++;
} else if (requestCode == 2002 && resultCode == RESULT_OK) {
Log.e(TAG,"data="+data.getData()+","+data.getDataString());
if (count == 2) {
Toast.makeText(mContext,"最多上传2张照片",Toast.LENGTH_SHORT).show();
return;
}
String str = FileLoadUtils.getCameraData(data);
Log.e(TAG,"str="+str);
pathList.add(str);
ImgGridAdapter imageAdapter = new ImgGridAdapter(mContext, pathList);
rv_health.setAdapter(imageAdapter);
rv_health.requestFocus();
count ++;
}
}
2. FileLoadUtils.java 工具类:
public class FileLoadUtils {
private static final String TAG = "FileLoadUtils";
public FileLoadUtils() {
}
public static String handleImageOnKitKat(Context context, Intent data) {
Uri uri = data.getData();
if (DocumentsContract.isDocumentUri(context, uri)) {
String docId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = docId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=" + id;
String type = docId.split(":")[0];
Uri contentUri = null;
if (type.equalsIgnoreCase("image")) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if (type.equalsIgnoreCase("audio")) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
} else if (type.equalsIgnoreCase("video")) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}
return getImagePath(context, contentUri, selection);
} else if ("com.android.providers.media.downloads.documents".equals(uri.getAuthority())) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
Long.valueOf(docId));
return getImagePath(context, contentUri, null);
} else if ("content".equals(uri.getAuthority())) {
return getImagePath(context, uri, null);
} else if ("file".equals(uri.getAuthority())) {
return uri.getPath();
}
}
return "";
}
private static String getImagePath(Context context, Uri uri, String selection) {
String path = null;
Cursor cursor = context.getContentResolver().query(uri, null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
public static Bitmap getimage(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
//现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
float hh = 800f;//这里设置高度为800f
float ww = 480f;//这里设置宽度为480f
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;//be=1表示不缩放
if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;//设置缩放比例
Log.e(TAG,"inSampleSize="+be);
//重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
}
public static Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int options = 90;
int length = baos.toByteArray().length / 1024;
Log.e(TAG,"length="+length);
if (length>5000){
//重置baos即清空baos
baos.reset();
//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
image.compress(Bitmap.CompressFormat.JPEG, 10, baos);
}else if (length>4000){
baos.reset();
image.compress(Bitmap.CompressFormat.JPEG, 20, baos);
}else if (length>3000){
baos.reset();
image.compress(Bitmap.CompressFormat.JPEG, 50, baos);
}else if (length>2000){
baos.reset();
image.compress(Bitmap.CompressFormat.JPEG, 70, baos);
}
Log.e(TAG,"baos.toByteArray().length="+baos.toByteArray().length);
//循环判断如果压缩后图片是否大于1M,大于继续压缩
while (baos.toByteArray().length / 1024>1024) {
//重置baos即清空baos
baos.reset();
//这里压缩options%,把压缩后的数据存放到baos中
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
//每次都减少10
options -= 10;
}
//把压缩后的数据baos存放到ByteArrayInputStream中
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
//把ByteArrayInputStream数据生成图片
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
return bitmap;
}
/**
* 保存bitmap到本地
* @param context the context
* @param mBitmap the m bitmap
* @return string
*/
public static String saveBitmap(Context context, Bitmap mBitmap) {
String savePath = Environment.getExternalStorageDirectory().toString() + "/nmpaapp/";
File filePic;
try {
filePic = new File(savePath + System.currentTimeMillis() + ".jpg");
Log.d("LUO", "图片地址====" + filePic);
if (!filePic.exists()) {
filePic.getParentFile().mkdirs();
filePic.createNewFile();
}
FileOutputStream fos = new FileOutputStream(filePic);
//不压缩,保存本地
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return filePic.getAbsolutePath();
}
/*
* 弹出框,选择是从本机选择图片还是拍照
* */
public static void showPhotoDialog (Activity mContext,int requestCode) {
View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_photo,null,false);
final AlertDialog dialog = new AlertDialog.Builder(mContext).setView(view).create();
TextView btn_cancel = view.findViewById(R.id.tv_confirm);
btn_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//... To-do
dialog.dismiss();
}
});
TextView tv_selPhoto = view.findViewById(R.id.tv_selPhoto);
tv_selPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
mContext.startActivityForResult(intent, requestCode);
dialog.dismiss();
}
});
TextView tv_takePhoto = view.findViewById(R.id.tv_takePhoto);
tv_takePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
takePhoto(mContext,requestCode+1);
dialog.dismiss();
}
});
dialog.show();
Window window = dialog.getWindow();
window.setGravity(Gravity.BOTTOM);
window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
window.getDecorView().setPadding(0, 0, 0, 0);
window.setBackgroundDrawable(null);
}
public static void takePhoto(Activity mContext, int requestCode) {
// 启动相机程序
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mContext.startActivityForResult(intent, requestCode);
}
/*
* 从拍照返回的数据中保存图片并返回图片路径
* */
public static String getCameraData(Intent data) {
String path = null;
Bitmap photo = null;
if (data.getData() != null || data.getExtras() != null) { // 防止没有返回结果
Uri uri = data.getData();
if (uri != null) {
photo = BitmapFactory.decodeFile(uri.getPath()); // 拿到图片
}
if (photo == null) {
Bundle bundle = data.getExtras();
if (bundle != null) {
photo = (Bitmap) bundle.get("data");
String saveDir = Environment.getExternalStorageDirectory().toString() + "/nmpaapp/";
String filename = System.currentTimeMillis() + ".jpg";
File file = new File(saveDir, filename);
FileOutputStream fileOutputStream = null;
// 打开文件输出流
try {
fileOutputStream = new FileOutputStream(file);
// 生成图片文件
photo.compress(Bitmap.CompressFormat.JPEG,
100, fileOutputStream);
path = file.getPath();
Log.e("FileLoadUtils", "str=" + path);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
return path;
}