现在的位置: 首页 > 综合 > 正文

Bitmap对象和字节数组的相互转换

2018年01月11日 ⁄ 综合 ⁄ 共 1090字 ⁄ 字号 评论关闭

      这样一个需求,自定义相机拍照后,发现图片相比实际效果逆时针旋转了90度,且mParameters.setRotation(rotation);无效果,所以就想把获取到的bitmap对象旋转90来实现正确的效果。


//data是字节数据,将其解析成位图

Bitmap b = BitmapFactory.decodeByteArray(data, 0, data.length);

现在我已经从字节流中获取了一个bitmap的对象,通过以下方法将其旋转90度:

public static Bitmap getRotateBitmap(Bitmap b, float rotateDegree){
Matrix matrix = new Matrix();
matrix.postRotate((float)rotateDegree);
Bitmap rotaBitmap = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, false);
return rotaBitmap;
}

那么现在能正确显示的Bitmap对象已经获得,剩下的就是把这个Bitmap对象(rotaBitmap)写入系统的图像数据库中。

ByteArrayOutputStream os2 = new ByteArrayOutputStream();

                        //通过这一句获取bitmap对象的字节流,写入到os2中
rotaBitmap.compress(CompressFormat.JPEG, 100, os2);

Uri imageUri = this.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new ContentValues());
try {
os = this.getContentResolver().openOutputStream(imageUri);
//os.write(data);

                        //向os中写入bitmap对象的字节数组,将存片存入数据库中

os.write(os2.toByteArray());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
os.flush();
os.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}




抱歉!评论已关闭.