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);
这是我的代码。它将图像上传到服务器。但是,我只能看到一个盒子。我哪里错了?
最佳答案
确保在最后转换回位图,即服务器端
1、将您的 ImageView 转换为位图。
imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
2、将bitmap转成base64字符串传给服务器
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,在服务器端将base64转换为位图。 (这是 java 代码,用你的服务器端语言来做)
byte[] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
设置此位图显示图像
关于java - 如何在android中将图像转换为base64字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36030867/