将imageview转换为base64字符串

时间:2013-11-20 04:55:34

标签: java android json

我可以在android imageview中使用base64字符串转换器吗? 如果是,那么如何..请帮助.. 我尝试使用以下代码..

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);

然后我想将img_str作为json数据发送到我的服务器..请帮助人

2 个答案:

答案 0 :(得分:0)

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);

答案 1 :(得分:0)

您需要执行两个步骤

<强> 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。将字节数组转换为base64字符串

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

干杯!!