Android打开手机相册选择图片加载与压缩和Sqlite存取

打开手机相册选择图片

调用手机相册管理应用

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值