我想将图像转换为字节数组,然后将该字节数组转换为字符串。此外,我想将该字符串转换回字节数组,最后返回到adroid中的图像。我怎么能完成这个?任何帮助将不胜感激。
这是将inputstream转换为字符串
private String convertInputStreamToString(InputStream in){
try {
byte[] b=new byte[8000];
in.read(b);
String base64String=Base64.encode(b);
return base64String;
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
这将字符串转换为输入流
String imageString =Settings.getCurrentUserImage(c);// it is the encoded string
byte[] bytearray = Base64.decode(imageString);
InputStream is =new ByteArrayInputStream(bytearray);
Drawable dUser = Drawable.createFromStream(is , "src");
userImg.setImageDrawable(dUser);
这是对的吗? 我在这行代码中有错误
InputStream is =new ByteArrayInputStream(bytearray);
错误是..
02-22 23:31:30.268: ERROR/AndroidRuntime(611): FATAL EXCEPTION: main
02-22 23:31:30.268: ERROR/AndroidRuntime(611): java.lang.NullPointerException
02-22 23:31:30.268: ERROR/AndroidRuntime(611): at java.io.ByteArrayInputStream.<init>(ByteArrayInputStream.java:58)
02-22 23:31:30.268: ERROR/AndroidRuntime(611): at aynoo.forms.FreindMessagesActivity.addMessage(FreindMessagesActivity.java:294)
02-22 23:31:30.268: ERROR/AndroidRuntime(611): at aynoo.forms.FreindMessagesActivity.getMessagesFromJSON(FreindMessagesActivity.java:459)
02-22 23:31:30.268: ERROR/AndroidRuntime(611): at aynoo.forms.FreindMessagesActivity.access$3(FreindMessagesActivity.java:433)
02-22 23:31:30.268: ERROR/AndroidRuntime(611): at aynoo.forms.FreindMessagesActivity$3.run(FreindMessagesActivity.java:190)
02-22 23:31:30.268: ERROR/AndroidRuntime(611): at android.os.Handler.handleCallback(Handler.java:587)
02-22 23:31:30.268: ERROR/AndroidRuntime(611): at android.os.Handler.dispatchMessage(Handler.java:92)
02-22 23:31:30.268: ERROR/AndroidRuntime(611): at android.os.Looper.loop(Looper.java:123)
02-22 23:31:30.268: ERROR/AndroidRuntime(611): at android.app.ActivityThread.main(ActivityThread.java:3647)
02-22 23:31:30.268: ERROR/AndroidRuntime(611): at java.lang.reflect.Method.invokeNative(Native Method)
02-22 23:31:30.268: ERROR/AndroidRuntime(611): at java.lang.reflect.Method.invoke(Method.java:507)
02-22 23:31:30.268: ERROR/AndroidRuntime(611): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-22 23:31:30.268: ERROR/AndroidRuntime(611): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-22 23:31:30.268: ERROR/AndroidRuntime(611): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
如果您使用的是2.2+,则可以使用Base64实用程序来完成此操作。如果您需要在较旧的设备上使用它,只需将Base64.java文件复制/粘贴到您的项目中,它的重量非常轻。