[英]how to convert an image into base64 string in android?
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?
我哪里错了?
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. 3,在服务器端将base64转换为位图。 (this is java code, do it in your server side language)
(这是java代码,用你的服务器端语言做)
byte[] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
set this bitmap to display image 设置此位图以显示图像
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.