人生难得几回搏,此时不搏待何时。这篇文章主要讲述Android中 Bitmap和Drawable相互转换的方法相关的知识,希望能为你提供帮助。
1、Drawable -->
Bitmap
[java] view plain copy
- Bitmap drawable2Bitmap(Drawable drawable) {
- if (drawable instanceof BitmapDrawable) {
- return ((BitmapDrawable) drawable).getBitmap();
- } else if (drawable instanceof NinePatchDrawable) {
- Bitmap bitmap = Bitmap
- .createBitmap(
- drawable.getIntrinsicWidth(),
- drawable.getIntrinsicHeight(),
- drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
- : Bitmap.Config.RGB_565);
- Canvas canvas = new Canvas(bitmap);
- drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
- drawable.getIntrinsicHeight());
- drawable.draw(canvas);
- return bitmap;
- } else {
- return null;
- }
- }
2、从资源中获取的Drawable --> Bitmap
[java] view plain copy
- Resources res = getResources();
- Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.pic);
3、Bitmap --> Drawable
[java] view plain copy
- Drawable bitmap2Drawable(Bitmap bitmap) {
- return new BitmapDrawable(bitmap);
- }
4、Bitmap --> byte[]
[java] view plain copy
- byte[] Bitmap2Bytes(Bitmap bm) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
- return baos.toByteArray();
- }
5、 byte[] --> Bitmap
[java] view plain copy
- Bitmap Bytes2Bimap(byte[] b) {
- if (b.length != 0) {
- return BitmapFactory.decodeByteArray(b, 0, b.length);
- } else {
- return null;
- }
- }
推荐阅读
- android解决Viewpager设置高度为wrap_content无效的方法
- Windows Server AppFabric分布式缓存研究
- [Android Studio 权威教程]配置出“NB”的Android Studio
- Appnium+C#+Winform自动化测试系列前言
- Android 5.x Theme 与 ToolBar 实战
- Android学习之——优化篇
- Android各种Adapter用法
- app模块设计
- 掌握最快捷的Android Studio使用方式