2012-02-17 60 views
0

我正在处理图像。在我的应用程序中,我已经显示了可绘制的图像,并将可绘制的图像设置为ImageView。当我点击一个按钮时,我想使用Base64将ImageView图像编码为字节码。如何通过使用Base64编码将ImageView图像转换为字节码?

我已经实现的代码如下:

((ImageView)findViewById(R.id.imageView1)).setImageResource(R.drawable.person); 

((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     ((TextView)findViewById(R.id.textView1)).setText("Get((ImageView)findViewById(R.id.imageView1)) image Base64.encode() here"); 
    } 
}); 

我怎样才能获得编码imageView1图像成字节码?

任何人都可以请帮助我。

回答

3

尝试......

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

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

该字符串现在设置你的TextView作为

tv.setText(img_str); 
+0

在编码到Base64时是否需要始终压缩图像?是否可以直接将图像/图像文件转换为Base64编码的字符串而不进行压缩? – VikramV 2014-01-14 12:10:49

1

使用本

public String encode(Bitmap icon) { 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     icon.compress(Bitmap.CompressFormat.PNG, 50, baos); 
     byte[] data = baos.toByteArray(); 
     String test = Base64.encodeBytes(data); 
     return test; 
    }` 
+0

我怎样才能在位图中获取imageView1? – 2012-02-17 09:43:44

+0

Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.person); – 2012-02-17 09:59:41

1

看看这段代码,

Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.person) 
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
bMap .compress(Bitmap.CompressFormat.PNG, 100, baos); 
//bMap is the bitmap object 
byte[] b = baos.toByteArray(); 
String encodedString = Base64.encodeToString(b, Base64.DEFAULT) 
相关问题