編輯:Android開發實例
本文實例講述了android圖片類型之間相互轉換實現代碼。分享給大家供大家參考。具體如下:
android在處理一寫圖片資源的時候,會進行一些類型的轉換,現在有空整理一下:
1、Drawable → Bitmap
Java代碼如下:
public static Bitmap drawableToBitmap(Drawable drawable) {
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);
//canvas.setBitmap(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
public static Bitmap drawableToBitmap(Drawable drawable) {
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);
//canvas.setBitmap(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
2、從資源中獲取Bitmap
Java代碼如下:
Resources res=getResources(); Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic); Resources res=getResources(); Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);
3、Bitmap → byte[]
Java代碼如下:
private byte[] Bitmap2Bytes(Bitmap bm){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
private byte[] Bitmap2Bytes(Bitmap bm){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
4、 byte[] → Bitmap
Java代碼如下:
private Bitmap Bytes2Bimap(byte[] b){
if(b.length!=0){
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
else {
return null;
}
}
private Bitmap Bytes2Bimap(byte[] b){
if(b.length!=0){
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
else {
return null;
}
}
以上是我在實踐中遇到的一些轉換,以後遇到類似的就不用到處找了。
希望本文所述對大家的Android程序設計有所幫助。
Android提高之AudioRecord實現助聽器的方法
通常來說,在進行Android項目開發的時候可以通過MediaRecorder和AudioRecord這兩個工具來實現錄音的功能,MediaRecorder直接把
深入淺析Android Fragment(下篇)
在上篇文章給大家介紹深入淺析Android Fragment(上篇),包括一些基本的用法和各種API,如果還想深入學習請繼續關注本篇文章。 本篇將介紹上篇提到的:
Android登錄實例
登錄應用程序的屏幕,詢問憑據登錄到一些特定的應用。可能需要登錄到Facebook,微博等本章介紹了,如何創建一個登錄界面,以及如何管理安全問題和錯誤嘗試。首先,必須定義兩
帶你實現開發者頭條(二) 實現左滑菜單
今天開始模仿開發者頭條的側滑菜單,是本系列第二篇文章,相信大家已經看到很多app使用這種側滑。今天我來教大家用Android自帶DrawerLayo