Drawable à byte []
-
09-10-2019 - |
Question
J'ai une image à partir du Web dans un ImageView
. Il est très petit (un favicon) et je voudrais le stocker dans ma base de données SQLite.
Je peux obtenir un Drawable
de mImageView.getDrawable()
mais je ne sais pas quoi faire. Je ne comprends pas bien la classe Drawable
dans Android.
Je sais que je peux obtenir un tableau d'octets d'un Bitmap
comme:
Bitmap defaultIcon = BitmapFactory.decodeStream(in);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitmapdata = stream.toByteArray();
Mais comment puis-je obtenir un tableau d'octets d'un Drawable
?
La solution
Drawable d; // the drawable (Captain Obvious, to the rescue!!!)
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitmapdata = stream.toByteArray();
Autres conseils
Merci à tous et cela a résolu mon problème.
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.my_pic);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitMapData = stream.toByteArray();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tester);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitMapData = stream.toByteArray();
Si Drawable est un BitmapDrawable vous pouvez essayer celui-ci.
long getSizeInBytes(Drawable drawable) {
if (drawable == null)
return 0;
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
return bitmap.getRowBytes() * bitmap.getHeight();
}
Bitmap.getRowBytes () renvoie le nombre d'octets entre les rangées dans les pixels de l'image bitmap.
Pour en savoir plus consulter ce projet: LazyList
File myFile = new File(selectedImagePath);
byte [] mybytearray = new byte [filelenghth];
BufferedInputStream bis1 = new BufferedInputStream(new FileInputStream(myFile));
bis1.read(mybytearray,0,mybytearray.length);
l'image est stockée dans le bytearray ..