2012-02-17 47 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) 
相關問題