打开手机相册选择图片
调用手机相册管理应用
mView.ivGoodsPic.setOnClickListener(view -> {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
});
在结果返回中取出选择的图片
如果不需要压缩,则直接decodeStream转成Bitmap即可。如果需要压缩,则在取到uri之后先执行压缩,再存储和赋值给ImageView
@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 {
Bitmap bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri));
mView.ivGoodsPic.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
showDialogError(e.getMessage());
}
}
super.onActivityResult(requestCode, resultCode, data);
}
图片压缩
这里先执行了尺寸压缩,再执行质量压缩
达到相对最佳的效果和大小
//创建 options 实例
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; //设置为true时,获取到的bitmap为null,只是存放宽高值
Bitmap bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri), null, options);
// 计算宽高缩放比例
int samplew = options.outWidth / 680;
int sampleh = options.outHeight / 510;
// 最终取大的那个为缩放比例,这样才能适配
// 设置缩放比例
options.inSampleSize = Math.max(samplew, sampleh);
options.inJustDecodeBounds = false; // 一定要记得将inJustDecodeBounds设为false,否则Bitmap为null
bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri), null, options);
//以上为尺寸压缩,接着再执行一次质量压缩
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 36, bos);
byte[] picData = bos.toByteArray();
Bitmap result = BitmapFactory.decodeByteArray(picData, 0, picData.length);
存储到数据库
因为Sqlite里想要存储图片的话只能使用BLOB数据类型,即是二进制类型,所以我们可以使用上面压缩时得到的ByteArrayOutputStream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 36, bos);
byte[] picData = bos.toByteArray();
如果你不想压缩,只是想把图片转成二进制,那把压缩质量36改成100即可,就是不让它压缩
读取数据库中的图片栏位
byte[] bytes = cursor.getBlob(cursor.getColumnIndex("store_pic"));
Bitmap goodspic = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
mView.ivGoodsPic.setImageBitmap(goodspic);