简体   繁体   English

将imageview转换为base64字符串

[英]Convert imageview into a base64 string

can i use base64 string converter in android imageview ? 我可以在android imageview中使用base64字符串转换器吗? if yes then how..please help.. i try out with this following code.. 如果是的话,那么如何..请帮助..我尝试下面的代码。

ImageView iv;
iv=(ImageView) findViewById(R.id.imageView1);
iv.buildDrawingCache();
Bitmap bitmap = iv.getDrawingCache();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image=stream.toByteArray();
String img_str = Base64.encodeToString(image, 0);

then i want to send img_str as a json data into my server..please help guys 然后我想将img_str作为json数据发送到我的服务器..请帮助伙计们

You can decode the string that you just encoded and get the image back by doing something like the following:

byte[] decodedString = Base64.decode(strBase64, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
image.setImageBitmap(decodedByte);

And u can send string to server this way :

 JSONObject jsonObj = new JSONObject(ur_string);

You need to do two steps 你需要做两个步骤

1. create byte array from ImageView (drawable) 1.从ImageView创建字节数组(可绘制)

Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.images);   
//R.drawable.images is image for my ImageView
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] imageByteArray=stream.toByteArray();
System.out.println("byte array:"+ imageByteArray);

2. convert byte array to base64 string 2.将字节数组转换为base64字符串

String img_str = Base64.encodeToString(imageByteArray, 0);
System.out.println("string:"+img_str);

Cheers!! 干杯!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM