2017-08-10 71 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做,请看我编辑的答案 –