我试图将图像保存到SQLite数据库中,但即使我压缩并重新缩放位图,文件仍然太大,尤其是当你从手机的相机拍摄图像时。
有没有办法将字节数组/位图压缩到一个特定的大小,比如从4mb到500kb?如果是,我该怎么做?
private void uriToFile(Uri uri, File sdImageMainDirectory) throws IOException {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
OutputStream stream = new FileOutputStream(sdImageMainDirectory);
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
int maxSize = 10;
float bitmapRatio = (float) bitmapWidth / (float) bitmapHeight;
if(bitmapRatio > 0){
bitmapWidth = maxSize;
bitmapHeight = (int) (bitmapWidth / bitmapRatio);
}
else{
bitmapHeight = maxSize;
bitmapWidth = (int) (bitmapHeight * bitmapRatio);
}
bitmap.createScaledBitmap(bitmap, bitmapWidth, bitmapHeight, true);
bitmap.compress(Bitmap.CompressFormat.JPEG, 30, stream);
stream.flush();
stream.close();
}
您实际上并没有压缩缩放后的图像,而是压缩原始图像。将最后四行更改为:
Bitmap scaled = bitmap.createScaledBitmap(bitmap, bitmapWidth, bitmapHeight, true);
scaled.compress(Bitmap.CompressFormat.JPEG, 30, stream);
stream.flush();
stream.close();
createScaledBitmap()
返回缩放后的位图,结果刚刚丢失。
您应该能够将maxSize
设置为1000,并且可以看到小于500k的文件大小。
您也可以使用这些代码
String[] filePathColumn = {MediaStore.Images.Media.DATA};
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
img_Decodable_Str = cursor.getString(columnIndex);
cursor.close();
**Bitmap bitmapImage = BitmapFactory.decodeFile(img_Decodable_Str);
Bitmap converetdImage = getResizedBitmap(bitmapImage, 500);**