android圖片處理

在 Android 應(yīng)用中加載位圖比較復(fù)雜,原因有很多種:

  • 位圖很容易就會耗盡應(yīng)用的內(nèi)存預(yù)算。例如,Pixel 手機上的相機拍攝的照片最大可達 4048x3036 像素(1200 萬像素)。如果使用的位圖配置為 [ARGB_8888](https://developer.android.com/reference/android/graphics/Bitmap.Config)(Android 2.3(API 級別 9)及更高版本的默認(rèn)設(shè)置),將單張照片加載到內(nèi)存大約需要 48MB 內(nèi)存(404830364 字節(jié))。如此龐大的內(nèi)存需求可能會立即耗盡該應(yīng)用的所有可用內(nèi)存。
  • 在界面線程中加載位圖會降低應(yīng)用的性能,導(dǎo)致響應(yīng)速度變慢,甚至?xí)?dǎo)致系統(tǒng)顯示 ANR 消息。因此,在使用位圖時,必須正確地管理線程處理。
    單個像素的字節(jié)大小
    單個像素的字節(jié)大小由Bitmap的一個可配置的參數(shù)Config來決定。 Bitmap中,存在一個枚舉類Config,定義了Android中支持的Bitmap配置:


    不同config單個像素字節(jié)大小.png

    Bitmap加載方式
    Bitmap 的加載方式有 Resource 資源加載、本地(SDcard)加載、網(wǎng)絡(luò)加載等加載方式。

  1. 從本地(SDcard)文件讀取
    方式一
    /**
  • 獲取縮放后的本地圖片 *
  • @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;
    options.inSampleSize = inSampleSize;
    return BitmapFactory.decodeFile(filePath, options);
    }
    方式二 (效率高于方式一)
    /
    *
  • 獲取縮放后的本地圖片 *
  • @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;
    }
  1. 從輸入流中讀取文件(網(wǎng)絡(luò)加載)
    /**
  • 獲取縮放后的本地圖片 *
  • @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);
    }
    3.Resource資源加載
    Res資源加載方式:
    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);
    }
    此種方式相當(dāng)?shù)暮馁M內(nèi)存 建議采用 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);
    }
    BitmapFactory.decodeResource 加載的圖片可能會經(jīng)過縮放,該縮放目前是放在 java 層做的,效率 比較低,而且需要消耗 java 層的內(nèi)存。因此,如果大量使用該接口加載圖片,容易導(dǎo)致OOM錯誤
    BitmapFactory.decodeStream 不會對所加載的圖片進行縮放,相比之下占用內(nèi)存少,效率更高。 這兩個接口各有用處,如果對性能要求較高,則應(yīng)該使用 decodeStream ;如果對性能要求不高,且需 要 Android 自帶的圖片自適應(yīng)縮放功能,則可以使用 decodeResource 。
    4.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;
    }
    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);
    }
    Bitmap | Drawable | InputStream | Byte[ ] 之間進行轉(zhuǎn)換
    1.Drawable轉(zhuǎn)化成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 的獲取方式: Drawable drawable=getResources().getDrawable(R.drawable.ic_launcher);
    2.Bitmap轉(zhuǎn)換成Drawable
    public static Drawable bitmapToDrawable(Resources resources, Bitmap bm) {
    Drawable drawable = new BitmapDrawable(resources, bm);
    return drawable;
    }
    3.Bitmap轉(zhuǎn)換成byte[ ]
    public byte[] bitmap2Bytes(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
    return baos.toByteArray();
    }
    4.byte[]轉(zhuǎn)換成Bitmap
    Bitmapbitmap=BitmapFactory.decodeByteArray(byte,0,b.length);
    5.InputStream轉(zhuǎn)換成Bitmap
    InputStreamis=getResources().openRawResource(id); Bitmapbitmap=BitmaoFactory.decodeStream(is);
    6.InputStream轉(zhuǎn)換成byte[]
    InputStream is = getResources().openRawResource(id);//也可以通過其他方式接收一個 InputStream對象
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] b = new byte[1024
    2];
    int len = 0;
    while ((len = is.read(b, 0, b.length)) != -1) {
    baos.write(b, 0, len);
    baos.flush(); }
    byte[] bytes = baos.toByteArray();
    Bitmap常用操作
    1.將Bitmap保存為本地文件:
    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();
    } }
    2.圖片壓縮:
    private static Bitmap compressImage(Bitmap image) {
    if (image == null) {
    return null;
    }
    ByteArrayOutputStream baos = null;
    try {
    baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 50, 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;
    }
    3.圖片縮放:
    /**
  • 根據(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;
    }
    4.獲取圖片旋轉(zhuǎn)角度:
    /
    *
  • 讀取照片exif信息中的旋轉(zhuǎn)角度 *
  • @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;
    }
    5.設(shè)置圖片旋轉(zhuǎn)角度
    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;
    }
    6.通過圖片id獲得Bitmap:
    Bitmapbitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    7.通過 assest 獲取 獲得Drawable bitmap:
    InputStream in = this.getAssets().open("ic_launcher");
    Drawable da = Drawable.createFromStream(in, null);
    Bitmap mm = BitmapFactory.decodeStream(in);
    8.通過 sdcard 獲得 bitmap
    1 Bitmapbit=BitmapFactory.decodeFile("/sdcard/android.jpg");
    9.view轉(zhuǎn)Bitmap
    publicstaticBitmapconvertViewToBitmap(Viewview,intbitmapWidth,int bitmapHeight){
    Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
    view.draw(new Canvas(bitmap));
    return bitmap;
    }
    10.將控件轉(zhuǎn)換為bitmap
    public static Bitmap convertViewToBitMap(View view){ // 打開圖像緩存
    view.setDrawingCacheEnabled(true);
    // 必須調(diào)用measure和layout方法才能成功保存可視組件的截圖到png圖像文件
    // 測量View大小
    view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    // 發(fā)送位置和尺寸到View及其所有的子View
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); // 獲得可視組件的截圖
    Bitmap bitmap = view.getDrawingCache();
    return bitmap;
    }
    public static Bitmap getBitmapFromView(View view){
    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(),
    view.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(returnedBitmap); Drawable bgDrawable = view.getBackground(); if (bgDrawable != null)
    bgDrawable.draw(canvas); else
    canvas.drawColor(Color.WHITE); view.draw(canvas);
    return returnedBitmap;
    }
    11.放大縮小圖片
    public static Bitmap zoomBitmap(Bitmap bitmap,int w,int h){ int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    Matrix matrix = new Matrix();
    float scaleWidht = ((float)w / width);
    float scaleHeight = ((float)h / height);
    matrix.postScale(scaleWidht, scaleHeight);
    Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,
    true);
    return newbmp;
    }
    12.獲得圓角圖片的方法
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap,float roundPx){
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap .getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(output);
    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect);
    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint);
    return output;
    }
    13.對 bitmap 進行裁剪
    public Bitmap bitmapClip(Context context , int id , int x , int y){
    Bitmap map = BitmapFactory.decodeResource(context.getResources(), id); map = Bitmap.createBitmap(map, x, y, 120, 120);
    return map;
    }
    Bitmap內(nèi)存模型


    內(nèi)存模型.png

    Bitmap的內(nèi)存回收

  1. 在Android2.3.3之前推薦使用Bitmap.recycle()方法進行Bitmap的內(nèi)存回收。
    備注:只有當(dāng)確定這個Bitmap不被引用的時候才能調(diào)用此方法,否則會有“Canvas: trying to use a recycled bitmap”這個錯誤。
  2. Android3.0之后
    Android3.0之后,并沒有強調(diào)Bitmap.recycle();而是強調(diào)Bitmap的復(fù)用
    Save a bitmap for later use
    使用LruCache對Bitmap進行緩存**,當(dāng)再次使用到這個Bitmap的時候直接獲取,而不用重走編碼流程。
    Use an existing bitmap
    Android3.0(API 11之后)引入了BitmapFactory.Options.inBitmap字段,設(shè)置此字段之后解 碼方法會嘗試復(fù)用一張存在的Bitmap。這意味著Bitmap的內(nèi)存被復(fù)用,避免了內(nèi)存的回收 及申請過程,顯然性能表現(xiàn)更佳。不過,使用這個字段有幾點限制:
    聲明可被復(fù)用的Bitmap必須設(shè)置inMutable為true;
    Android4.4(API 19)之前只有格式為jpg、png,同等寬高(要求苛刻),inSampleSize為1的 Bitmap才可以復(fù)用;
    Android4.4(API 19)之前被復(fù)用的Bitmap的inPreferredConfig會覆蓋待分配內(nèi)存的Bitmap設(shè) 置的inPreferredConfig;
    Android4.4(API 19)之后被復(fù)用的Bitmap的內(nèi)存必須大于需要申請內(nèi)存的Bitmap的內(nèi)存; Android4.4(API 19)之前待加載Bitmap的Options.inSampleSize必須明確指定為1
    獲取Bitmap的大小
  3. getByteCount()
    getByteCount()方法是在API12加入的,代表存儲Bitmap的色素需要的最少內(nèi)存。API19開始 getAllocationByteCount()方法代替了getByteCount()。
  4. getAllocationByteCount()
    API19之后,Bitmap加了一個Api:getAllocationByteCount();代表在內(nèi)存中為Bitmap分配的內(nèi)存大
    小。
    public final int getAllocationByteCount() {
    if (mBuffer == null) {
    //mBuffer代表存儲Bitmap像素數(shù)據(jù)的字節(jié)數(shù)組。
    return getByteCount();
    }
    return mBuffer.length; }
  5. getByteCount()與getAllocationByteCount()的區(qū)別
    一般情況下兩者是相等的
    通過復(fù)用Bitmap來解碼圖片,如果被復(fù)用的Bitmap的內(nèi)存比待分配內(nèi)存的Bitmap大,那么 getByteCount()表示新解碼圖片占用內(nèi)存的大小(并非實際內(nèi)存大小,實際大小是復(fù)用的那個 Bitmap的大小),getAllocationByteCount()表示被復(fù)用Bitmap真實占用的內(nèi)存大小(即mBuffer 的長度)
    Bitmap占用內(nèi)存大小計算
    Bitmap作為位圖,需要讀入一張圖片每一個像素點的數(shù)據(jù),其主要占用內(nèi)存的地方也正是這些像素數(shù) 據(jù)。對于像素數(shù)據(jù)總大小,我們可以猜想為:像素總數(shù)量 × 每個像素的字節(jié)大小,而像素總數(shù)量在矩形 屏幕表現(xiàn)下,應(yīng)該是:橫向像素數(shù)量 × 縱向像素數(shù)量,結(jié)合得到:
    Bitmap內(nèi)存占用 ≈ 像素數(shù)據(jù)總大小 = 橫向像素數(shù)量 × 縱向像素數(shù)量 × 每個像素的字節(jié)大小
    if (env->GetBooleanField(options, gOptions_scaledFieldID)) {
    const int density = env->GetIntField(options, gOptions_densityFieldID);
    const int targetDensity = env->GetIntField(options, gOptions_targetDensityFieldID);
    const int screenDensity = env->GetIntField(options, gOptions_screenDensityFieldID);
    if (density != 0 && targetDensity != 0 && density != screenDensity) {
    scale = (float) targetDensity / density;
    }
    }
    ...
    int scaledWidth = decoded->width();
    int scaledHeight = decoded->height();

if (willScale && mode != SkImageDecoder::kDecodeBounds_Mode) {
scaledWidth = int(scaledWidth * scale + 0.5f);
scaledHeight = int(scaledHeight * scale + 0.5f);
}
...
if (willScale) {
const float sx = scaledWidth / float(decoded->width());
const float sy = scaledHeight / float(decoded->height());
bitmap->setConfig(decoded->getConfig(), scaledWidth, scaledHeight);
bitmap->allocPixels(&javaAllocator, NULL);
bitmap->eraseColor(0);
SkPaint paint;
paint.setFilterBitmap(true);
SkCanvas canvas(bitmap);
canvas.scale(sx, sy);
canvas.drawBitmap(
decoded, 0.0f, 0.0f, &paint);
}
從上述代碼中,我們看到bitmap最終通過canvas繪制出來,而canvas在繪制之前,有一個scale的操作,scale的值由
scale=(float)targetDensity/density;
這一行代碼決定,即縮放的倍率和targetDensity和density相關(guān),而這兩個參數(shù)都是從傳入的options中 獲取到的
inDensity:Bitmap位圖自身的密度、分辨率
inTargetDensity: Bitmap最終繪制的目標(biāo)位置的分辨率
inScreenDensity: 設(shè)備屏幕分辨率
其中inDensity和圖片存放的資源文件的目錄有關(guān),同一張圖片放置在不同目錄下會有不同的值:

density.png

可以驗證幾個結(jié)論:

  1. 圖片放在drawable中,等同于放在drawable-mdpi中,原因為:drawable目錄不具有屏幕密度特
    性,所以采用基準(zhǔn)值,即mdpi
  2. 圖片放在某個特定drawable中,比如drawable-hdpi,如果設(shè)備的屏幕密度高于當(dāng)前drawable目
    錄所代表的密度,則圖片會被放大,否則會被縮小 放大或縮小比例 = 設(shè)備屏幕密度 / drawable目錄所代表的屏幕密度
    因此,關(guān)于Bitmap占用內(nèi)存大小的公式,從之前:
    Bitmap內(nèi)存占用 ≈ 像素數(shù)據(jù)總大小 = 橫向像素數(shù)量 × 縱向像素數(shù)量 × 每個像素的字節(jié)大小
    可以更細(xì)化為:
    Bitmap內(nèi)存占用 ≈ 像素數(shù)據(jù)總大小 = 圖片寬 × 圖片高× (設(shè)備分辨率/資源目錄分辨率)^2 × 每個像 素的字節(jié)大小
    高效加載大型位圖,請參考官網(wǎng)
    https://developer.android.com/topic/performance/graphics/load-bitmap
    緩存位圖,請參考官網(wǎng)
    https://developer.android.com/topic/performance/graphics/cache-bitmap
    管理位圖,請參考官網(wǎng)
    https://developer.android.com/topic/performance/graphics/manage-memory
    本篇參考了http://www.itdecent.cn/p/3f6f6e4f1c88
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容