編輯:關於 Android 程式設計
「更換頭像」大概是每個 App 都有的功能:讓使用者拍照或從相冊挑一張,裁切成指定比例後顯示在 ImageView 上(實務上通常還要上傳到伺服器)。這個流程看似簡單,卻牽涉到 Uri 取得、相機 Intent 與裁剪 Intent 的串接,中間任何一步處理不當都會拿到模糊縮圖或直接 crash。
以下程式碼參考網上資料並結合專案實況整理,在多款機型上測試過,暫時沒有發現嚴重問題。程式碼已附上註解:
public class UploadPicActivity extends Activity implements View.OnClickListener {
private Button take_photo_btn;
private Button select_photo_btn;
private ImageView photo_iv;
// 相機拍照
public static final int TAKE_PHOTO_CODE = 1;
// 相冊選圖
public static final int SELECT_PIC_CODE = 2;
// 圖片裁剪
private static final int PHOTO_CROP_CODE = 3;
private Uri photoUri; // 圖片的 Uri
private String picPath; // 圖片檔案路徑
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_pic);
initViews();
}
private void initViews() {
this.take_photo_btn = (Button) findViewById(R.id.take_photo_btn);
this.take_photo_btn.setOnClickListener(this);
this.select_photo_btn = (Button) findViewById(R.id.select_photo_btn);
this.select_photo_btn.setOnClickListener(this);
this.photo_iv = (ImageView) findViewById(R.id.photo_iv);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.take_photo_btn: // 拍照
picTyTakePhoto();
break;
case R.id.select_photo_btn: // 選圖庫
pickPhoto();
break;
}
}
/**
* 拍照取得圖片
*/
private void picTyTakePhoto() {
// 先確認 SDCard 存在
String SDState = Environment.getExternalStorageState();
if (SDState.equals(Environment.MEDIA_MOUNTED)) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
/**
* 使用相機拍照,照片會存入相簿。
* 這種方式的好處是:拿到的是拍照後的原圖。
* 若不透過 ContentValues 保存照片路徑,拍照後取得的會是縮圖,可能不清晰。
*/
ContentValues values = new ContentValues();
photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(intent, TAKE_PHOTO_CODE);
} else {
Toast.makeText(this, "內存卡不存在", Toast.LENGTH_LONG).show();
}
}
/**
* 從相冊取得圖片
*/
private void pickPhoto() {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, SELECT_PIC_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
// 相冊選圖(部分機型有相容性問題,請留意)
if (requestCode == SELECT_PIC_CODE) {
if (null != data && null != data.getData()) {
photoUri = data.getData();
picPath = uriToFilePath(photoUri);
startPhotoZoom(photoUri, PHOTO_CROP_CODE);
} else {
Toast.makeText(this, "圖片選擇失敗", Toast.LENGTH_LONG).show();
}
}
// 拍照回來
else if (requestCode == TAKE_PHOTO_CODE) {
String[] pojo = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
cursor.moveToFirst();
picPath = cursor.getString(columnIndex);
if (Build.VERSION.SDK_INT < 14) {
cursor.close();
}
}
if (picPath != null) {
photoUri = Uri.fromFile(new File(picPath));
startPhotoZoom(photoUri, PHOTO_CROP_CODE);
} else {
Toast.makeText(this, "圖片選擇失敗", Toast.LENGTH_LONG).show();
}
}
// 裁剪完成
else if (requestCode == PHOTO_CROP_CODE) {
if (photoUri != null) {
Bitmap bitmap = BitmapFactory.decodeFile(picPath);
if (bitmap != null) {
// 這裡可以把圖片上傳到伺服器
photo_iv.setImageBitmap(bitmap);
}
}
}
}
}
/**
* 呼叫系統裁剪
*/
private void startPhotoZoom(Uri uri, int REQUE_CODE_CROP) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true"); // 開啟裁剪模式
intent.putExtra("scale", true); // 去黑邊
intent.putExtra("scaleUpIfNeeded", true);
intent.putExtra("aspectX", 3); // 寬高比例,依需求調整
intent.putExtra("aspectY", 2);
intent.putExtra("outputX", 600); // 輸出的寬(像素)
intent.putExtra("outputY", 400); // 輸出的高(像素)
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true); // 關閉人臉識別
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra("return-data", false); // 不透過 data 回傳,避免 OOM
startActivityForResult(intent, REQUE_CODE_CROP);
}
/**
* Uri 轉檔案路徑
*/
private String uriToFilePath(Uri uri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, proj, null, null, null);
int image_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(image_index);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<Button
android:id="@+id/take_photo_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="拍照"
android:textSize="16sp"/>
<Button
android:id="@+id/select_photo_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="選擇圖片"
android:textSize="16sp"/>
<ImageView
android:id="@+id/photo_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"/>
</LinearLayout>
<uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
requestPermissions() 主動請求,並處理使用者拒絕的分支。file:// URI 傳給其他 App,會直接拋 FileUriExposedException。必須改用 FileProvider.getUriForFile() 產生 content:// URI,並在 AndroidManifest.xml 宣告 provider 與 file_paths.xml。com.android.camera.action.CROP 是非官方 action,越來越多機型(尤其原生 Android 11 以上)找不到對應的處理者。建議改用 uCrop、Android-Image-Cropper 這類專門的裁剪庫,API 更穩定,也能自行控制 UI。WRITE_EXTERNAL_STORAGE 也不再是萬靈丹。
Android VectorDrawable 與 SVG:動手做兩個炫酷的向量動畫
Android 從 5.0 開始提供了新的 API VectorDrawable,讓我們可以直接使用向量圖 SVG。在 XML 檔中,透過 <vector>、
Android Studio 技巧:給 LogCat 換上高辨識度的配色
LogCat 默認配色偏素,各級別日誌混在一起時很不醒目。花一分鐘改一下顏色,排查問題的效率會明顯提升。 一、先看效果 二、設置步驟 打開 File → Setti
Android 產品研發:APK 代碼混淆與資源混淆實務指南
為什麼需要混淆Android 應用上線後,APK 很容易被反編譯。若程式碼沒有保護,業務邏輯、介面結構與關鍵呼叫都可能被快速還原。混淆的目的,是把類名、方法名與資源名稱轉
Android 五大布局入門:屬性、適用場景與取捨
Android 提供了五種基礎布局來控制子控件的排列方式:LinearLayout(線性布局)、RelativeLayout(相對布局)、TableLayout(表格布局