我试图捕获从webview.capturePicture()获取的图片,将其保存到sqlite数据库中,为此,我需要将图像转换为字节[],才能将其保存为表中的blob,然后通过检索该字节[]并将其转换回位图。
我在做的是:
Picture p = webView.capturePicture();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
p.writeToStream(bos);
byte[] ba = bos.toByteArray());
然后我通过以下方式检索图像:
byte[] image = cursor.getBlob(imageColumnIndex);
Bitmap bm = BitmapFactory.decodeByteArray(image, 0, image.length);
我可以很好地检索字节[],但是我总是从bitmapfactory得到一个空位图。
我还注意到,如果我记录.d(tag,“+bos”),我会得到一个预期的长字节序列,但是如果我在执行bos.tobyterarray()之后对b a执行同样的操作,我只会得到一个短数组,比如:[b@2b0a7c60
我猜我很难把outputstream转换成bytearray。这可能是因为capturePiture()方法返回的是outputStream而不是byteArrayOutputStream吗?
任何帮助都将不胜感激。
最佳答案
使用以下两个函数convert:::
public String convertBitmapToString(Bitmap src) {
String str =null;
if(src!= null){
ByteArrayOutputStream os=new ByteArrayOutputStream();
src.compress(android.graphics.Bitmap.CompressFormat.PNG, 100,(OutputStream) os);
byte[] byteArray = os.toByteArray();
str = Base64.encodeToString(byteArray,Base64.DEFAULT);
}
return str;
}
public static Bitmap getBitMapFromString(String src) {
Bitmap bitmap = null;
if(src!= null){
byte[] decodedString = Base64.decode(src.getBytes(), Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(decodedString,0,decodedString.length);
}
return bitmap;
}
更新:
//Convert Picture to Bitmap
private static Bitmap pictureDrawable2Bitmap(Picture picture){
PictureDrawable pictureDrawable = new PictureDrawable(picture);
Bitmap bitmap = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(),pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(pictureDrawable.getPicture());
return bitmap;
}