Вопрос

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.

Это было полезно?

Решение

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;
    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top