java 如何在android中将图像转换为base64字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36030867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to convert an image into base64 string in android?
提问by Gowtham Bk
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.image);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
final String encodedImage = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
This is my code. It uploads the image onto the server. However, All I can see is a box. Where am I going wrong?
这是我的代码。它将图像上传到服务器。然而,我只能看到一个盒子。我哪里错了?
回答by Joseph Joseph
Make sure you convert back to bitmap at the End, ie Server side
确保在最后转换回位图,即服务器端
1, convert your imageview to bitmap.
1、将你的imageview转换为位图。
imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
2, convert bitmap to base64 String and pass to server
2、位图转base64 String传给服务器
public String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
byte[] byteFormat = stream.toByteArray();
// get the base 64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
return imgString;
}
3, At server side convert base64 to bitmap. (this is java code, do it in your server side language)
3,在服务器端将base64转换为位图。(这是java代码,用你的服务器端语言做)
byte[] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
set this bitmap to display image
设置此位图以显示图像
回答by Joseph Joseph
convert your image to bitmap.
将您的图像转换为位图。
File imagefile = new File(Environment.getExternalStorageDirectory(),"/image/test.jpg" );
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
logger.error(Log.getStackTraceString(e));
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
Bitmap to Byte[]
位图到字节[]
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 10 , baos);
byte[] img = baos.toByteArray();
Byte[] to String:
字节 [] 到字符串:
String s= Base64.encodeToString(img , Base64.DEFAULT)