国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

Android圖片緩存之Bitmap詳解(一)

2019-12-12 05:50:09
字體:
來源:轉載
供稿:網(wǎng)友

前言:
最近準備研究一下圖片緩存框架,基于這個想法覺得還是先了解有關圖片緩存的基礎知識,今天重點學習一下Bitmap、BitmapFactory這兩個類。 

Bitmap:
Bitmap是Android系統(tǒng)中的圖像處理的最重要類之一。用它可以獲取圖像文件信息,進行圖像剪切、旋轉、縮放等操作,并可以指定格式保存圖像文件。
 重要函數(shù)
 •public void recycle() // 回收位圖占用的內存空間,把位圖標記為Dead
 •public final boolean isRecycled() //判斷位圖內存是否已釋放  
 •public final int getWidth()//獲取位圖的寬度 
 •public final int getHeight()//獲取位圖的高度
 •public final boolean isMutable()//圖片是否可修改 
 •public int getScaledWidth(Canvas canvas)//獲取指定密度轉換后的圖像的寬度 
 •public int getScaledHeight(Canvas canvas)//獲取指定密度轉換后的圖像的高度 
 •public boolean compress(CompressFormat format, int quality, OutputStream stream)//按指定的圖片格式以及畫質,將圖片轉換為輸出流。 
 format:Bitmap.CompressFormat.PNG或Bitmap.CompressFormat.JPEG 
 quality:畫質,0-100.0表示最低畫質壓縮,100以最高畫質壓縮。對于PNG等無損格式的圖片,會忽略此項設置。
 •public static Bitmap createBitmap(Bitmap src) //以src為原圖生成不可變得新圖像 
 •public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)//以src為原圖,創(chuàng)建新的圖像,指定新圖像的高寬以及是否可變。 
 •public static Bitmap createBitmap(int width, int height, Config config)――創(chuàng)建指定格式、大小的位圖 
 •public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height)以source為原圖,創(chuàng)建新的圖片,指定起始坐標以及新圖像的高寬。 

BitmapFactory工廠類:
Option 參數(shù)類:
 •public boolean inJustDecodeBounds//如果設置為true,不獲取圖片,不分配內存,但會返回圖片的高度寬度信息。
 •public int inSampleSize//圖片縮放的倍數(shù)
 •public int outWidth//獲取圖片的寬度值
 •public int outHeight//獲取圖片的高度值 
 •public int inDensity//用于位圖的像素壓縮比 
 •public int inTargetDensity//用于目標位圖的像素壓縮比(要生成的位圖) 
 •public byte[] inTempStorage //創(chuàng)建臨時文件,將圖片存儲
 •public boolean inScaled//設置為true時進行圖片壓縮,從inDensity到inTargetDensity
 •public boolean inDither //如果為true,解碼器嘗試抖動解碼
 •public Bitmap.Config inPreferredConfig //設置解碼器
 •public String outMimeType //設置解碼圖像
 •public boolean inPurgeable//當存儲Pixel的內存空間在系統(tǒng)內存不足時是否可以被回收
 •public boolean inInputShareable //inPurgeable為true情況下才生效,是否可以共享一個InputStream
 •public boolean inPreferQualityOverSpeed  //為true則優(yōu)先保證Bitmap質量其次是解碼速度
 •public boolean inMutable //配置Bitmap是否可以更改,比如:在Bitmap上隔幾個像素加一條線段
 •public int inScreenDensity //當前屏幕的像素密度 

 工廠方法:
 •public static Bitmap decodeFile(String pathName, Options opts) //從文件讀取圖片 
 •public static Bitmap decodeFile(String pathName)
 •public static Bitmap decodeStream(InputStream is) //從輸入流讀取圖片
 •public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts)
 •public static Bitmap decodeResource(Resources res, int id) //從資源文件讀取圖片
 •public static Bitmap decodeResource(Resources res, int id, Options opts) 
 •public static Bitmap decodeByteArray(byte[] data, int offset, int length) //從數(shù)組讀取圖片
 •public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts)
 •public static Bitmap decodeFileDescriptor(FileDescriptor fd)//從文件讀取文件 與decodeFile不同的是這個直接調用JNI函數(shù)進行讀取 效率比較高
 •public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) 

Bitmap.Config inPreferredConfig : 
枚舉變量 (位圖位數(shù)越高代表其可以存儲的顏色信息越多,圖像越逼真,占用內存越大)
 •public static final Bitmap.Config ALPHA_8 //代表8位Alpha位圖        每個像素占用1byte內存
 •public static final Bitmap.Config ARGB_4444 //代表16位ARGB位圖  每個像素占用2byte內存
 •public static final Bitmap.Config ARGB_8888 //代表32位ARGB位圖  每個像素占用4byte內存
 •public static final Bitmap.Config RGB_565 //代表8位RGB位圖          每個像素占用2byte內存

Android中一張圖片(BitMap)占用的內存主要和以下幾個因數(shù)有關:圖片長度,圖片寬度,單位像素占用的字節(jié)數(shù)。

一張圖片(BitMap)占用的內存=圖片長度*圖片寬度*單位像素占用的字節(jié)數(shù) 

圖片讀取實例:
 1.)從文件讀取方式一 

 /**  * 獲取縮放后的本地圖片  *  * @param filePath 文件路徑  * @param width 寬  * @param height 高  * @return  */ public static Bitmap readBitmapFromFile(String filePath, int width, int height) {  BitmapFactory.Options options = new BitmapFactory.Options();  options.inJustDecodeBounds = true;  BitmapFactory.decodeFile(filePath, options);  float srcWidth = options.outWidth;  float srcHeight = options.outHeight;  int inSampleSize = 1;  if (srcHeight > height || srcWidth > width) {   if (srcWidth > srcHeight) {    inSampleSize = Math.round(srcHeight / height);   } else {    inSampleSize = Math.round(srcWidth / width);   }  }  options.inJustDecodeBounds = false;  options.inSampleSize = inSampleSize;  return BitmapFactory.decodeFile(filePath, options); }

 2.)從文件讀取方式二 效率高于方式一 

/**  * 獲取縮放后的本地圖片  *  * @param filePath 文件路徑  * @param width 寬  * @param height 高  * @return  */ public static Bitmap readBitmapFromFileDescriptor(String filePath, int width, int height) {  try {   FileInputStream fis = new FileInputStream(filePath);   BitmapFactory.Options options = new BitmapFactory.Options();   options.inJustDecodeBounds = true;   BitmapFactory.decodeFileDescriptor(fis.getFD(), null, options);   float srcWidth = options.outWidth;   float srcHeight = options.outHeight;   int inSampleSize = 1;   if (srcHeight > height || srcWidth > width) {    if (srcWidth > srcHeight) {     inSampleSize = Math.round(srcHeight / height);    } else {     inSampleSize = Math.round(srcWidth / width);    }   }   options.inJustDecodeBounds = false;   options.inSampleSize = inSampleSize;   return BitmapFactory.decodeFileDescriptor(fis.getFD(), null, options);  } catch (Exception ex) {  }  return null; }

測試同樣生成10張圖片兩種方式耗時比較 cpu使用以及內存占用兩者相差無幾 第二種方式效率高一點 所以建議優(yōu)先采用第二種方式 

  start = System.currentTimeMillis();  for (int i = 0; i < testMaxCount; i++) {   BitmapUtils.readBitmapFromFile(filePath, 400, 400);  }  end = System.currentTimeMillis();  Log.e(TAG, "BitmapFactory decodeFile--time-->" + (end - start));  start = System.currentTimeMillis();  for (int i = 0; i < testMaxCount; i++) {   BitmapUtils.readBitmapFromFileDescriptor(filePath, 400, 400);  }  end = System.currentTimeMillis();  Log.e(TAG, "BitmapFactory decodeFileDescriptor--time-->" + (end - start));

3.)從輸入流中讀取文件 

 /**  * 獲取縮放后的本地圖片  *  * @param ins 輸入流  * @param width 寬  * @param height 高  * @return  */ public static Bitmap readBitmapFromInputStream(InputStream ins, int width, int height) {  BitmapFactory.Options options = new BitmapFactory.Options();  options.inJustDecodeBounds = true;  BitmapFactory.decodeStream(ins, null, options);  float srcWidth = options.outWidth;  float srcHeight = options.outHeight;  int inSampleSize = 1;  if (srcHeight > height || srcWidth > width) {   if (srcWidth > srcHeight) {    inSampleSize = Math.round(srcHeight / height);   } else {    inSampleSize = Math.round(srcWidth / width);   }  }  options.inJustDecodeBounds = false;  options.inSampleSize = inSampleSize;  return BitmapFactory.decodeStream(ins, null, options); }

4.)從資源文件中讀取文件  

 public static Bitmap readBitmapFromResource(Resources resources, int resourcesId, int width, int height) {  BitmapFactory.Options options = new BitmapFactory.Options();  options.inJustDecodeBounds = true;  BitmapFactory.decodeResource(resources, resourcesId, options);  float srcWidth = options.outWidth;  float srcHeight = options.outHeight;  int inSampleSize = 1;  if (srcHeight > height || srcWidth > width) {   if (srcWidth > srcHeight) {    inSampleSize = Math.round(srcHeight / height);   } else {    inSampleSize = Math.round(srcWidth / width);   }  }  options.inJustDecodeBounds = false;  options.inSampleSize = inSampleSize;  return BitmapFactory.decodeResource(resources, resourcesId, options); }

 此種方式相當?shù)暮馁M內存 建議采用decodeStream代替decodeResource 可以如下形式 

 public static Bitmap readBitmapFromResource(Resources resources, int resourcesId, int width, int height) {  InputStream ins = resources.openRawResource(resourcesId);  BitmapFactory.Options options = new BitmapFactory.Options();  options.inJustDecodeBounds = true;  BitmapFactory.decodeStream(ins, null, options);  float srcWidth = options.outWidth;  float srcHeight = options.outHeight;  int inSampleSize = 1;  if (srcHeight > height || srcWidth > width) {   if (srcWidth > srcHeight) {    inSampleSize = Math.round(srcHeight / height);   } else {    inSampleSize = Math.round(srcWidth / width);   }  }  options.inJustDecodeBounds = false;  options.inSampleSize = inSampleSize;  return BitmapFactory.decodeStream(ins, null, options); }

decodeStream、decodeResource占用內存對比: 

 start = System.currentTimeMillis();  for (int i = 0; i < testMaxCount; i++) {   BitmapUtils.readBitmapFromResource(getResources(), R.mipmap.ic_app_center_banner, 400, 400);   Log.e(TAG, "BitmapFactory decodeResource--num-->" + i);  }  end = System.currentTimeMillis();  Log.e(TAG, "BitmapFactory decodeResource--time-->" + (end - start));  start = System.currentTimeMillis();  for (int i = 0; i < testMaxCount; i++) {   BitmapUtils.readBitmapFromResource1(getResources(), R.mipmap.ic_app_center_banner, 400, 400);   Log.e(TAG, "BitmapFactory decodeStream--num-->" + i);  }  end = System.currentTimeMillis();  Log.e(TAG, "BitmapFactory decodeStream--time-->" + (end - start));

BitmapFactory.decodeResource 加載的圖片可能會經(jīng)過縮放,該縮放目前是放在 java 層做的,效率比較低,而且需要消耗 java 層的內存。因此,如果大量使用該接口加載圖片,容易導致OOM錯誤。
BitmapFactory.decodeStream 不會對所加載的圖片進行縮放,相比之下占用內存少,效率更高。
 這兩個接口各有用處,如果對性能要求較高,則應該使用 decodeStream;如果對性能要求不高,且需要 Android 自帶的圖片自適應縮放功能,則可以使用 decodeResource。 

5. )從二進制數(shù)據(jù)讀取圖片 

public static Bitmap readBitmapFromByteArray(byte[] data, int width, int height) {  BitmapFactory.Options options = new BitmapFactory.Options();  options.inJustDecodeBounds = true;  BitmapFactory.decodeByteArray(data, 0, data.length, options);  float srcWidth = options.outWidth;  float srcHeight = options.outHeight;  int inSampleSize = 1;  if (srcHeight > height || srcWidth > width) {   if (srcWidth > srcHeight) {    inSampleSize = Math.round(srcHeight / height);   } else {    inSampleSize = Math.round(srcWidth / width);   }  }  options.inJustDecodeBounds = false;  options.inSampleSize = inSampleSize;  return BitmapFactory.decodeByteArray(data, 0, data.length, options); }

6.)從assets文件讀取圖片 

 /**  * 獲取縮放后的本地圖片  *  * @param filePath 文件路徑  * @return  */ public static Bitmap readBitmapFromAssetsFile(Context context, String filePath) {  Bitmap image = null;  AssetManager am = context.getResources().getAssets();  try {   InputStream is = am.open(filePath);   image = BitmapFactory.decodeStream(is);   is.close();  } catch (IOException e) {   e.printStackTrace();  }  return image; }

圖片保存文件: 

 public static void writeBitmapToFile(String filePath, Bitmap b, int quality) {  try {   File desFile = new File(filePath);   FileOutputStream fos = new FileOutputStream(desFile);   BufferedOutputStream bos = new BufferedOutputStream(fos);   b.compress(Bitmap.CompressFormat.JPEG, quality, bos);   bos.flush();   bos.close();  } catch (IOException e) {   e.printStackTrace();  } }

圖片壓縮: 

 private static Bitmap compressImage(Bitmap image) {  if (image == null) {   return null;  }  ByteArrayOutputStream baos = null;  try {   baos = new ByteArrayOutputStream();   image.compress(Bitmap.CompressFormat.JPEG, 100, baos);   byte[] bytes = baos.toByteArray();   ByteArrayInputStream isBm = new ByteArrayInputStream(bytes);   Bitmap bitmap = BitmapFactory.decodeStream(isBm);   return bitmap;  } catch (OutOfMemoryError e) {  } finally {   try {    if (baos != null) {     baos.close();    }   } catch (IOException e) {   }  }  return null; }

圖片縮放: 

 /**  * 根據(jù)scale生成一張圖片  *  * @param bitmap  * @param scale 等比縮放值  * @return  */ public static Bitmap bitmapScale(Bitmap bitmap, float scale) {  Matrix matrix = new Matrix();  matrix.postScale(scale, scale); // 長和寬放大縮小的比例  Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);  return resizeBmp; }

獲取圖片旋轉角度: 

 /**  * 讀取照片exif信息中的旋轉角度  *  * @param path 照片路徑  * @return角度  */ private static int readPictureDegree(String path) {  if (TextUtils.isEmpty(path)) {   return 0;  }  int degree = 0;  try {   ExifInterface exifInterface = new ExifInterface(path);   int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);   switch (orientation) {    case ExifInterface.ORIENTATION_ROTATE_90:     degree = 90;     break;    case ExifInterface.ORIENTATION_ROTATE_180:     degree = 180;     break;    case ExifInterface.ORIENTATION_ROTATE_270:     degree = 270;     break;   }  } catch (Exception e) {  }  return degree; }

圖片旋轉角度: 

  private static Bitmap rotateBitmap(Bitmap b, float rotateDegree) {    if (b == null) {      return null;    }    Matrix matrix = new Matrix();    matrix.postRotate(rotateDegree);    Bitmap rotaBitmap = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true);    return rotaBitmap;  }

圖片轉二進制:

public byte[] bitmap2Bytes(Bitmap bm) {    ByteArrayOutputStream baos = new ByteArrayOutputStream();    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);    return baos.toByteArray();  } 

Bitmap轉Drawable

public static Drawable bitmapToDrawable(Resources resources, Bitmap bm) {    Drawable drawable = new BitmapDrawable(resources, bm);    return drawable;  } 

Drawable轉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);    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());    drawable.draw(canvas);    return bitmap;  }

Drawable、Bitmap占用內存探討
 之前一直使用過Afinal 和Xutils 熟悉這兩框架的都知道,兩者出自同一人,Xutils是Afina的升級版,AFinal中的圖片內存緩存使用的是Bitmap 而后來為何Xutils將內存緩存的對象改成了Drawable了呢?我們一探究竟 
寫個測試程序: 

 List<Bitmap> bitmaps = new ArrayList<>();    start = System.currentTimeMillis();    for (int i = 0; i < testMaxCount; i++) {      Bitmap bitmap = BitmapUtils.readBitMap(this, R.mipmap.ic_app_center_banner);      bitmaps.add(bitmap);      Log.e(TAG, "BitmapFactory Bitmap--num-->" + i);    }    end = System.currentTimeMillis();    Log.e(TAG, "BitmapFactory Bitmap--time-->" + (end - start));    List<Drawable> drawables = new ArrayList<>();        start = System.currentTimeMillis();    for (int i = 0; i < testMaxCount; i++) {      Drawable drawable = getResources().getDrawable(R.mipmap.ic_app_center_banner);      drawables.add(drawable);      Log.e(TAG, "BitmapFactory Drawable--num-->" + i);    }    end = System.currentTimeMillis();    Log.e(TAG, "BitmapFactory Drawable--time-->" + (end - start));

測試數(shù)據(jù)1000 同一張圖片

從測試說明Drawable 相對Bitmap有很大的內存占用優(yōu)勢。這也是為啥現(xiàn)在主流的圖片緩存框架內存緩存那一層采用Drawable作為緩存對象的原因。
 小結:圖片處理就暫時學習到這里,以后再做補充。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 黄平县| 彭水| 洞头县| 昌吉市| 宁波市| 哈密市| 云和县| 微博| 潞城市| 邳州市| 澎湖县| 化州市| 林西县| 沙洋县| 汽车| 沧州市| 柳林县| 五指山市| 陕西省| 铅山县| 中西区| 绥中县| 广元市| 历史| 彰化市| 玉田县| 进贤县| 庆安县| 大英县| 大足县| 凭祥市| 广饶县| 庄河市| 共和县| 遂川县| 莱芜市| 沅陵县| 沅陵县| 无锡市| 青铜峡市| 施秉县|