2017-08-10 96 views
-2

我有一個應用程序,我從通知中獲取小圖標並將其轉換爲字節[]並將其設置爲imageview結果白色圖像。我如何解決這個問題。 代碼: -將drawable轉換爲bytearray並將byte []轉換爲位圖後,它將顯示位圖爲白色?

Context remotePackageContext = null; 
    Bitmap bmp = null; 
    try { 
     PackageManager manager = getPackageManager(); 
     Resources resources = manager.getResourcesForApplication(pack); 
     Drawable icon = resources.getDrawable(id1); 
     if(icon !=null) { 
      bmp = ((BitmapDrawable) icon).getBitmap(); 
      ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
      bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); 
      byteArray = stream.toByteArray(); 
     } 

    } catch (PackageManager.NameNotFoundException e) { 
     e.printStackTrace(); 
    } 
+0

,因爲我已經把它在SQLite的 – Niraj

回答

0

據我瞭解,你要轉換可繪製爲位圖嗎? 你爲什麼不直接將其轉換,請嘗試使用此:

public static Bitmap drawableToBitmap(Drawable drawable) { 
    Bitmap bitmap = null; 
    try { 
     if (drawable instanceof BitmapDrawable) { 
      BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; 
      if (bitmapDrawable.getBitmap() != null) { 
       bitmap = bitmapDrawable.getBitmap(); 
       return bitmap; 
      } 
     } 

     if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) { 
      bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel 
     } else { 
      bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); 
     } 

     Canvas canvas = new Canvas(bitmap); 
     drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); 
     drawable.draw(canvas); 
    } catch (Exception e) { 
     CommonUtils.firebaseCrashReport(e); 
    } 
    return bitmap; 
} 

//另一種方式

public static Bitmap getDrawableToBitmap(Context context, int drawableId) { 
    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), 
      drawable); 
    return bitmap; 
} 
+0

我使用的byte [] outImage = notficationModel.getNotificationImage( );如果(outImage!= null){ Bitmap imageStream = BitmapFactory.decodeByteArray(outImage,0,outImage.length); holder.m_notificationImage.setImageBitmap(imageStream); } – Niraj

+0

但這是全白的結果圖像。顏色 – Niraj

+0

可能是你的圖像本身是白色backggroud ....或者如果你想使用任何可繪製文件夾的圖像,你可以通過繪製的ID做,請看我編輯的答案 –