Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android Bitmap核心操作大全:圓角、縮放、壓縮與縮略圖

編輯:Android 開發實例

Bitmap 是 Android 圖片處理的核心類,項目裡幾乎繞不開它。本文把日常開發中最常用的幾類操作整理在一起:生成圓角圖片、生成縮略圖、對圖片尺寸與體積進行壓縮,以及從 SD 卡讀取圖片。代碼裡每一步都做了註釋,方便查閱。

注意:測試其中某一個方法時,最好把其餘相關代碼註釋掉,避免相互干擾。

package com.testbitmapscale;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ImageView;

// 方法:
// 1 生成圓角 Bitmap 圖片
// 2 生成 Bitmap 縮略圖
// 3 壓縮圖片的長寬以及 kB
public class MainActivity extends Activity {
    private ImageView imageView;
    private Bitmap copyRawBitmap1;
    private Bitmap copyRawBitmap2;
    private Bitmap copyRawBitmap3;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        imageView = (ImageView) findViewById(R.id.imageView);

        // 第一種方式: 從資源文件中得到圖片
        Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.haha);
        copyRawBitmap1 = rawBitmap;
        copyRawBitmap2 = rawBitmap;
        copyRawBitmap3 = rawBitmap;

        // 第二種方式: 從 SD 卡中得到圖片(方法1)
        String SDCardPath = Environment.getExternalStorageDirectory().toString();
        String filePath = SDCardPath + "/" + "haha.jpg";
        Bitmap rawBitmap1 = BitmapFactory.decodeFile(filePath, null);

        // 第二種方式: 從 SD 卡中得到圖片(方法2)
        InputStream inputStream = getBitmapInputStreamFromSDCard("haha.jpg");
        Bitmap rawBitmap2 = BitmapFactory.decodeStream(inputStream);

        // ----> 以下為將圖片設置圓角
        Bitmap roundCornerBitmap = this.toRoundCorner(rawBitmap, 40);
        imageView.setImageBitmap(roundCornerBitmap);
        // ----> 以上為將圖片設置圓角

        // ----> 以下為將圖片高寬和大小(kB)壓縮
        int rawHeight = rawBitmap.getHeight();
        int rawWidth = rawBitmap.getWidth();
        int newHeight = 500;
        int newWidth = 500;
        float heightScale = ((float) newHeight) / rawHeight;
        float widthScale = ((float) newWidth) / rawWidth;
        Matrix matrix = new Matrix();
        matrix.postScale(heightScale, widthScale);
        // matrix.postRotate(-30);      // 設置旋轉角度
        // matrix.postSkew(0.1f, 0.1f); // 設置傾斜
        Bitmap newBitmap = Bitmap.createBitmap(rawBitmap, 0, 0, rawWidth, rawWidth, matrix, true);
        Drawable newBitmapDrawable = new BitmapDrawable(newBitmap);
        imageView.setImageDrawable(newBitmapDrawable);
        this.compressAndSaveBitmapToSDCard(newBitmap, "xx100.jpg", 80);
        // 問題: 原圖 625x690 90.2kB,設為 500x500 壓縮後反而變成 171kB。
        // 原因是 compress() 的 quality 參數設得太大(如 100),常用 80 即可。
        // ----> 以上為將圖片高寬和大小(kB)壓縮

        // ----> 以下為將圖片的 kB 壓縮,寬高不變
        this.compressAndSaveBitmapToSDCard(copyRawBitmap1, "0011fa.jpg", 80);
        // ----> 以上為將圖片的 kB 壓縮,寬高不變

        // ----> 以下為獲取 SD 卡圖片的縮略圖方法1
        String SDCardPath1 = Environment.getExternalStorageDirectory().toString();
        String filePath1 = SDCardPath1 + "/" + "haha.jpg";
        Bitmap bitmapThumbnail1 = this.getBitmapThumbnail(filePath1);
        imageView.setImageBitmap(bitmapThumbnail1);
        // ----> 以上為獲取 SD 卡圖片的縮略圖方法1

        // ----> 以下為獲取 SD 卡圖片的縮略圖方法2
        String SDCardPath2 = Environment.getExternalStorageDirectory().toString();
        String filePath2 = SDCardPath2 + "/" + "haha.jpg";
        Bitmap tempBitmap = BitmapFactory.decodeFile(filePath2);
        Bitmap bitmapThumbnail2 = ThumbnailUtils.extractThumbnail(tempBitmap, 100, 100);
        imageView.setImageBitmap(bitmapThumbnail2);
        // ----> 以上為獲取 SD 卡圖片的縮略圖方法2
    }

    // 讀取 SD 卡下的圖片
    private InputStream getBitmapInputStreamFromSDCard(String fileName) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String SDCardPath = Environment.getExternalStorageDirectory().toString();
            String filePath = SDCardPath + File.separator + fileName;
            File file = new File(filePath);
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                return fileInputStream;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    // 獲取 SDCard 的目錄路徑
    private String getSDCardPath() {
        String SDCardPath = null;
        boolean IsSDcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        if (IsSDcardExist) {
            SDCardPath = Environment.getExternalStorageDirectory().toString();
        }
        return SDCardPath;
    }

    // 壓縮且保存圖片到 SDCard
    private void compressAndSaveBitmapToSDCard(Bitmap rawBitmap, String fileName, int quality) {
        String saveFilePaht = this.getSDCardPath() + File.separator + fileName;
        File saveFile = new File(saveFilePaht);
        if (!saveFile.exists()) {
            try {
                saveFile.createNewFile();
                FileOutputStream fileOutputStream = new FileOutputStream(saveFile);
                if (fileOutputStream != null) {
                    // compress(format, quality, stream)
                    // quality 為 0-100,0 意味著小尺寸壓縮,100 意味著高質量壓縮
                    rawBitmap.compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream);
                }
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 獲取圖片的縮略圖(通過 inSampleSize 進行降採樣)
    private Bitmap getBitmapThumbnail(String filePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;   // 只解析邊界信息,不分配內存
        Bitmap rawBitmap = BitmapFactory.decodeFile(filePath, options);
        // inSampleSize 表示縮略圖為原圖的幾分之一
        int sampleSize = computeSampleSize(options, 150, 200 * 200);
        options.inJustDecodeBounds = false;
        options.inSampleSize = sampleSize;
        Bitmap thumbnailBitmap = BitmapFactory.decodeFile(filePath, options);
        this.compressAndSaveBitmapToSDCard(thumbnailBitmap, "15.jpg", 80);
        return thumbnailBitmap;
    }

    // 計算 sampleSize
    public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }
        return roundedSize;
    }

    private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;
        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));
        if (upperBound < lowerBound) {
            return lowerBound;
        }
        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    /**
     * @param bitmap 需要修改的圖片
     * @param pixels 圓角的弧度
     * @return 圓角圖片
     */
    public Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
        Bitmap roundCornerBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(roundCornerBitmap);
        int color = 0xff424242;
        Paint paint = new Paint();
        paint.setColor(color);
        paint.setAntiAlias(true);   // 防止鋸齒
        Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        RectF rectF = new RectF(rect);
        float roundPx = pixels;
        canvas.drawARGB(0, 0, 0, 0);    // 相當於清屏
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);   // 先畫一個帶圓角的矩形
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);           // 再把原圖片畫上去
        return roundCornerBitmap;
    }
}

幾個實用要點總結一下:圓角是通過「先畫圓角矩形、再用 SRC_IN 混合模式把原圖貼上去」實現的;縮略圖的關鍵在 inSampleSize 降採樣,能在解碼階段就大幅降低內存佔用,比先加載再縮放聰明得多;而壓縮時 quality 參數別盲目設 100,80 往往就能兼顧清晰度與體積。掌握這幾招,日常圖片處理基本夠用了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved