打开图片库
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
获取选择的图片
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
} catch (FileNotFoundException e) {
showDialogError(e.getMessage());
}
}
super.onActivityResult(requestCode, resultCode, data);
}
图片压缩
ContentResolver contentResolver = this.getContentResolver();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri), null, options);
int samplew = options.outWidth / 680;
int sampleh = options.outHeight / 680;
options.inSampleSize = Math.max(samplew, sampleh);
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri), null, options);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 36, bos);
picData = bos.toByteArray();
Bitmap result = BitmapFactory.decodeByteArray(picData, 0, picData.length);
mView.ivGoodsPic.setImageBitmap(result);
完整代码
mView.ivGoodsPic.setOnClickListener(view -> {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
});
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri uri = data.getData();
ContentResolver contentResolver = this.getContentResolver();
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri), null, options);
int samplew = options.outWidth / 680;
int sampleh = options.outHeight / 680;
options.inSampleSize = Math.max(samplew, sampleh);
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri), null, options);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 36, bos);
picData = bos.toByteArray();
Bitmap result = BitmapFactory.decodeByteArray(picData, 0, picData.length);
mView.ivGoodsPic.setImageBitmap(result);
} catch (FileNotFoundException e) {
showDialogError(e.getMessage());
}
}
super.onActivityResult(requestCode, resultCode, data);
}
|