Image encoding and Decoding using Base64 in android application

后端 未结 2 1509
忘掉有多难
忘掉有多难 2021-01-06 12:32

In my application I have faced a small issue in encoding and decoding images to String and pass it to web service. After getting the bitmap image, I convert it into

2条回答
  •  没有蜡笔的小新
    2021-01-06 13:10

    In the case of OutOfMemoryError, below code helps me.

    public String BitMapToString(Bitmap bitmap){
            ByteArrayOutputStream baos=new  ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,100, baos);
            byte [] b=baos.toByteArray();
            String temp=null;
            try{
            System.gc();
            temp=Base64.encodeToString(b, Base64.DEFAULT);
            }catch(Exception e){
                e.printStackTrace();
            }catch(OutOfMemoryError e){
                baos=new  ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG,50, baos);
                b=baos.toByteArray();
                temp=Base64.encodeToString(b, Base64.DEFAULT);
                Log.e("EWN", "Out of memory error catched");
            }
            return temp;
      }
    

    Basically what i did is : i catch OutofMemoryError and in that catch block i resize it by 50% and then i encode it to string.

提交回复
热议问题