2013-03-10 92 views
22

嗨,我有一個Base64格式的字符串。我想將它轉換爲位圖,然後將其顯示到ImageView。這是代碼:Android將位圖設置爲Imageview

ImageView user_image; 
Person person_object; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.user_profile_screen); 

    // ImageViews 
    user_image = (ImageView) findViewById(R.id.userImageProfile); 

    Bundle data = getIntent().getExtras(); 
    person_object = data.getParcelable("person_object"); 
    // getPhoto() function returns a Base64 String 
    byte[] decodedString = Base64.decode(person_object.getPhoto(), Base64.DEFAULT); 

    Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
    user_image.setImageBitmap(decodedByte); 
    } 

此代碼獲得Base64字符串成功,我沒有得到任何錯誤。但它不顯示圖像。 有什麼問題? 感謝

+0

請嘗試添加此行:user_image.setScaleType(ScaleType.FIT_XY); – KEYSAN 2013-03-10 16:02:56

+0

它是否適用於資源圖片?例如,如果您編寫'iuser_image.setImageResource(android.R.drawable.ic_delete)',它會顯示任何內容嗎? – vorrtex 2013-03-10 16:42:46

回答

29

請試試這個:

byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP); 
InputStream inputStream = new ByteArrayInputStream(decodedString); 
Bitmap bitmap = BitmapFactory.decodeStream(inputStream); 
user_image.setImageBitmap(bitmap); 
+1

感謝您的回覆。但它沒有奏效。我想我正確地轉換爲位圖。在將位圖設置爲視圖之後,它是否需要重新繪製才能在屏幕上看到? – kgnkbyl 2013-03-10 15:37:36

+0

你能看到那個圖像嗎? – Anjula 2013-09-08 14:28:32

6

有一個名爲畢加索庫,能夠有效地從URL加載圖像。它也可以從文件加載圖像。

實例:

  1. 加載URL到ImageView的,而不會產生一個位圖:通過產生位圖

    Picasso.with(context) // Context 
         .load("http://abc.imgur.com/gxsg.png") // URL or file 
         .into(imageView); // An ImageView object to show the loaded image 
    
  2. 負載網址的ImageView:

    Picasso.with(this) 
         .load(artistImageUrl) 
         .into(new Target() { 
          @Override 
          public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) { 
           /* Save the bitmap or do something with it here */ 
    
           // Set it in the ImageView 
           theView.setImageBitmap(bitmap) 
          } 
    
          @Override 
          public void onBitmapFailed(Drawable errorDrawable) { 
    
          } 
    
          @Override 
          public void onPrepareLoad(Drawable placeHolderDrawable) { 
    
          } 
         }); 
    

有更多選擇在畢加索可用的離子。 Here is the documentation

相關問題