基准错误-尝试发送图像时出现64错误

时间:2019-06-24 21:41:47

标签: java android wifi

我希望在两个设备之间共享页面的屏幕截图。屏幕截图存储在位图中,然后我将其转换为字节数组,然后在Base 64中将其转换为String。然后将String发送给将显示图像的处理程序。在尝试对图像进行解码后,它给了我一个:java.lang.IllegalArgumentException:糟糕的base-64

我已经尝试过以不同的方式发送图像,并尝试了所有不同的Base 64方法,例如Base64.DEFAULT,URLSAFE,NOPADDING等...

在此处创建屏幕截图并发送:

Bitmap b = 
Screenshot.takescreenshotofRootView(MainActivity.imageView);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG,100,baos);
byte[] bytea = baos.toByteArray();
String temp = Base64.encodeToString(bytea, Base64.DEFAULT);
sendReceive.write(temp.getBytes());

这是我要处理数据的地方

Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
   case MESSAGE_READ:
       MainActivity.imageView.setImageBitmap(bitm);
       byte[] readBuff = (byte[]) msg.obj;
       String tempMsg = new String(readBuff, 0, msg.arg1);
       byte [] encodeByte = Base64.decode(tempMsg,Base64.URL_SAFE);
       Bitmap bitms 
    = BitmapFactory.decodeByteArray(encodeByte,0,encodeByte.length);
       MainActivity.imageView.setImageBitmap(bitms);
       break;
        }
        return true;
    }
});

1 个答案:

答案 0 :(得分:0)

您可能会在未意识到的情况下遇到OutOfMemoryError,从而使base64字符串无效。您应该使用try / catch块包装代码,以查看是否正在发生这种情况。这是我的一些代码示例:

    String imageString = "";

    try {
        if (this.theBitmap != null) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            this.theBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] bytes = stream.toByteArray();
            imageString = Base64.encodeToString(bytes, Base64.DEFAULT);
        }

    }catch(OutOfMemoryError E){
        Log.e("MyApp", "Out Of Memory error");
    }