Image to Byte Array to String (and vice versa) in android?
I'd like to convert an image into a byte array, then convert that byte array into a string. Also, I'd then like to convert that string back to a byte array, and finally back to an image in adroid . How might I go about accomplishing this? Any help will be appreciated.
this is to convert inputstream to string
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 "";
}
}
and this to开发者_Python百科 convert string to inputstream
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);
is this correct ?! I have error in this line of code
InputStream is =new ByteArrayInputStream(bytearray);
where the error is ..
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)
If you are using 2.2+ you can use the Base64 utility to do exactly this. If you need it on older devices just copy/paste the Base64.java file to your project its really light weight.
精彩评论