Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 圖片編輯與處理(一):挑圖、降採樣與位圖繪製

編輯:關於 Android 程式設計

一、用系統內建相簿挑選圖片

最省事的方式是發一個 ACTION_PICK 意圖,把選擇工作交給系統相簿:

package com.example.testphotoedit;

import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity implements OnClickListener {

    private ImageView chosenImageView, copyPicture;
    private Button choosePicture;
    private Uri imageFileUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);
        choosePicture = (Button) findViewById(R.id.button_chose);
        chosenImageView = (ImageView) findViewById(R.id.chose_picture);
        copyPicture = (ImageView) findViewById(R.id.copy_picture);
        choosePicture.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.button_chose) {
            // 啟動相簿應用程式
            Intent chooseIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(chooseIntent, 0);
        }
    }
}

二、兩段式解碼:先量尺寸,再載入

挑到圖之後,最大的風險是記憶體。這裡示範一個重要技巧:先只讀取圖片的邊界資訊,據以計算縮放倍率,再正式解碼。

/* 在返回的意圖資料中取得所選圖片的 URI */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        imageFileUri = data.getData();

        Display currentDisplay = getWindowManager().getDefaultDisplay();
        int dw = currentDisplay.getWidth() / 2 - 100;
        int dh = currentDisplay.getHeight() / 2 - 100;

        try {
            BitmapFactory.Options bmpFactory = new BitmapFactory.Options();

            // 第一次:只載入尺寸,不載入圖片本身
            bmpFactory.inJustDecodeBounds = true;
            Bitmap bmp = BitmapFactory.decodeStream(
                    getContentResolver().openInputStream(imageFileUri),
                    null, bmpFactory);

            int heightRatio = (int) Math.ceil(bmpFactory.outHeight / (float) dh);
            int widthRatio = (int) Math.ceil(bmpFactory.outWidth / (float) dw);

            if (heightRatio > 1 && widthRatio > 1) {
                if (heightRatio > widthRatio) {
                    bmpFactory.inSampleSize = heightRatio;
                } else {
                    bmpFactory.inSampleSize = widthRatio;
                }
            }

            // 第二次:正式載入圖片
            bmpFactory.inJustDecodeBounds = false;
            bmp = BitmapFactory.decodeStream(
                    getContentResolver().openInputStream(imageFileUri),
                    null, bmpFactory);

            chosenImageView.setImageBitmap(bmp);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

這裡取 heightRatio 與 widthRatio 中的較大值作為 inSampleSize,確保縮完之後兩個方向都還能塞進目標框內——代價是圖片可能略小於理想尺寸,但绝不会超出可用區域。這是記憶體與畫質之間的合理取捨。

三、在位圖上繪製位圖

複製一張圖最直觀的做法:建立一張同尺寸的新 Bitmap,用 Canvas 把原圖畫上去。

Bitmap alteredBitmap = Bitmap.createBitmap(
        bmp.getWidth(), bmp.getWidth(), bmp.getConfig());
Canvas canvas = new Canvas(alteredBitmap);
Paint paint = new Paint();
canvas.drawBitmap(bmp, 0, 0, paint);
copyPicture.setImageBitmap(alteredBitmap);

這裡有個小疏漏值得指出:第三行建立新 Bitmap 時寬度寫了 bmp.getWidth() 兩次,高度也應該用 bmp.getHeight(),否則非正方形的圖會被拉伸變形。

對應的配置檔

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.testphotoedit.MainActivity$PlaceholderFragment">

    <Button
        android:id="@+id/button_chose"
        android:layout_width="120dp"
        android:layout_height="60dp"
        android:text="選擇圖片" />

    <ImageView
        android:id="@+id/chose_picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button_chose" />

    <ImageView
        android:id="@+id/copy_picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/chose_picture" />
</RelativeLayout>

另外提醒兩點:使用 ACTION_PICK 時通常不需額外權限,但若要讀取外部儲存中的任意檔案,仍應視 Android 版本補上讀取權限;而 getDefaultDisplay() 在 API 30 之後已不建議使用,改以 WindowMetrics 取得螢幕尺寸較為恰當。

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