Android - How to convert picture from webview.capturePicture() to byte[] and back to bitmap

送分小仙女□ 提交于 2019-12-21 05:28:12

问题


I'm trying to capture the picture I'm getting from webview.capturePicture() to save it to an sqliteDatabase, to do I need to convert the image to a byte[] to be able to save it as a BLOB in my table, and then by able to retrieve that byte[] and convert it back to a bitmap.

Here is what I'm doing:

Picture p = webView.capturePicture();  
ByteArrayOutputStream bos = new ByteArrayOutputStream();  
p.writeToStream(bos);

byte[] ba = bos.toByteArray());

I then retrieve the image by:

byte[] image = cursor.getBlob(imageColumnIndex);
Bitmap bm = BitmapFactory.decodeByteArray(image, 0, image.length);

I'm able to retrieve the byte[] just fine but I get a null bitmap all the time from bitmapfactory.

I also notice that if I log.d(TAG, ""+bos) I get a long sequence of bytes as expected but if I do the same to ba just after I do bos.toByteArray() I just get a short array, some thing like this: [B@2b0a7c60

I'm guessing I'm having trouble perhaps to convert by OutputStream to byteArray. Could this by because capturePiture() method returns an OutputStream instead of a ByteArrayOutputStream?

Any help would be appreciated.


回答1:


Use the below two function 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;
}

Updated::

//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;
    }


来源:https://stackoverflow.com/questions/10273646/android-how-to-convert-picture-from-webview-capturepicture-to-byte-and-bac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!