編輯:關於 Android 程式設計
這個示例實現三件事:調用系統相機拍照、對照片做壓縮、從本地相冊中挑選圖片。由於要讀取相冊內容,需要申請讀取外部存儲的權限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
public class MainActivity extends Activity implements View.OnClickListener {
private Button mButtonTakePhoto;
private Button mButtonGetPhoto;
private ImageView mImageViewPhoto;
private File mFile; // 存儲圖片的文件
public static final int GET_PIC_FROM_CAMERA = 0x123;
public static final int GET_PIC_FROM_GALLERY = 0x124;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonTakePhoto = (Button) findViewById(R.id.button_take_photo);
mButtonGetPhoto = (Button) findViewById(R.id.button_get_photo);
mImageViewPhoto = (ImageView) findViewById(R.id.imageView_camera);
mButtonTakePhoto.setOnClickListener(this);
mButtonGetPhoto.setOnClickListener(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case GET_PIC_FROM_CAMERA:
if (resultCode == RESULT_OK) {
ImageZip.zipImage(mFile.getAbsolutePath()); // 壓縮圖片
mImageViewPhoto.setImageURI(Uri.fromFile(mFile));
}
break;
case GET_PIC_FROM_GALLERY:
if (resultCode == RESULT_OK) {
getImageFromGallery(data);
}
break;
}
}
/** 從本地相冊中選擇並取得相片 */
private void getImageFromGallery(Intent data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close(); // 用完及時關閉,避免資源洩漏
// 相冊原圖往往過大,不能直接展示,先壓縮
ImageZip.zipImage(picturePath);
mImageViewPhoto.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_take_photo:
getPictureFromCamera();
break;
case R.id.button_get_photo:
// 左起參數:選擇行為,以及系統相冊的 URI
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, GET_PIC_FROM_GALLERY);
break;
}
}
/** 向 onActivityResult 發起請求,取得拍攝生成的圖片 */
private void getPictureFromCamera() {
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
// 確定存儲拍照結果的文件路徑
mFile = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
try {
mFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
startActivityForResult(intent, GET_PIC_FROM_CAMERA);
}
}
public class ImageZip {
/** 壓縮圖片並原地覆蓋 */
public static void zipImage(String savePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // 只讀取邊界信息,不真正加載像素
BitmapFactory.decodeFile(savePath, options);
options.inSampleSize = computeInitialSampleSize(options, 480, 480 * 960);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(savePath, options);
try {
FileOutputStream fos = new FileOutputStream(savePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
bitmap.recycle();
bitmap = null;
System.gc();
}
/** 只解壓縮後的 Bitmap,不落盤 */
public static Bitmap getZipImage(String savePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(savePath, options);
options.inSampleSize = computeInitialSampleSize(options, 480, 480 * 960);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(savePath, options);
bitmap.recycle();
bitmap = null;
System.gc();
return bitmap;
}
public 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;
}
public 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;
}
}
}
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/button_take_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Take Photo" />
<Button
android:id="@+id/button_get_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Get from Gallery" />
</LinearLayout>
<ImageView
android:id="@+id/imageView_camera"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
要點回顧:相冊選圖用 Intent.ACTION_PICK 搭配 EXTERNAL_CONTENT_URI,返回後通過 ContentResolver 查詢 MediaStore.Images.Media.DATA 拿到真實路徑;壓縮的核心技巧是兩次解碼——第一次設 inJustDecodeBounds = true 只取尺寸信息,算出合適的 inSampleSize 後再真正加載像素,這樣能在不解出大位圖的前提下完成降採樣,有效規避 OOM。
Android Fragment 與 Activity 的雙向溝通與生命週期全解析
Fragment 與 Activity 之間的互動關係 每一個 Fragment 實例都與承載它的 Activity 綁定在一起,兩者天生就存在密切的關聯。Fragmen
Android 學習筆記 037:基於 TCP 的 Socket 通信
前面說過,Android 客戶端與服務端通信有兩種主要方式:HTTP 通信和 Socket 通信。HTTP 已經介紹過,這次來學 Socket。而在動手之前,得先把 TC
Android 反射機制實戰:用 Class.forName 動態呼叫方法做計算機
本文以一個加減乘除計算機為例,示範如何在 Android 中用 Java 反射機制動態取得類別、建立實例並呼叫方法。 先搞懂什麼是反射 Java 反射機制的定義是:在運
如何用 Toolbar 取代 ActionBar:完整實戰指南
從 Android 3.0 開始,App Bar 的功能逐漸被整合進 ActionBar,而 ActionBar 被包含在 Theme 中。對開發者而言,這缺乏靈活性,而