在Android应用程序中使用Base64进行图像编码和解码

Sri*_*san 3 android android-widget

在我的应用程序中,我遇到了一个小问题,即将图像编码和解码为String并将其传递给Web服务.获取位图图像后,我将其转换为byte []并编码为String值但在某些情况下它显示错误我不知道它为什么会出现.还有一个疑问是Base64类仅支持将Bitmap图像转换为String或任何其他可用的工具.

提前致谢...

raj*_*ara 12

在OutOfMemoryError的情况下,下面的代码可以帮助我.

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;
  }
Run Code Online (Sandbox Code Playgroud)

基本上我所做的是:我捕获OutofMemoryError并在该catch块中我将其调整大小50%然后我将其编码为字符串.