編輯:關於 Android 程式設計
目標是完成一條完整的圖片鏈路:從相簿挑選或拍照取得圖片,把圖片上傳到伺服器,之後再從伺服器把它讀回來顯示。
一般來說有兩種方式:
從相簿選擇
原理比較單純:從系統取得照片,轉成位元組後再生成 Bitmap 物件用於顯示。
拍照取得
拍照的原理其實是「先拍攝並儲存,再讀取」,讀取的部分就和從相簿選圖一樣。
點擊頭像時,先彈出一個 Dialog 讓使用者選擇來源:
private final CharSequence[] its = {"拍照", "從相冊選擇"};
headImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new AlertDialog.Builder(ModiUserInfoActivity.this)
.setTitle("更換頭像")
.setItems(its, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
switch (which) {
case 0: // 拍照
break;
case 1: // 從相冊選擇
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, SELECT_PIC);
break;
}
}
})
.create()
.show();
}
});
接著在 onActivityResult() 處理回傳的圖片資料:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case SELECT_PIC: // 相簿
Bitmap photo = data.getParcelableExtra("data");
if (photo != null) {
headImage = Common.zoomBitmap(photo, 85, 85);
UserController.updateHeadImage(userId, headImage, handler);
photo.recycle();
}
break;
case SELECT_CAMERA: // 相機
try {
// 啟動裁剪
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(photoFile, "image/*");
intent.putExtra("scale", true);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 80);
intent.putExtra("outputY", 80);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoFile);
// 廣播刷新相冊
Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intentBc.setData(photoFile);
sendBroadcast(intentBc);
startActivityForResult(intent, CROP_PHOTO);
} catch (Exception e) {
e.printStackTrace();
}
break;
case CROP_PHOTO:
try {
Bitmap bitmap = BitmapFactory.decodeStream(
getContentResolver().openInputStream(photoFile));
headImage = Common.zoomBitmap(bitmap, 85, 85);
UserController.updateHeadImage(userId, headImage, handler);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
要注意的是,隱式 Intent 的 com.android.camera.action.CROP 並非所有機型都支援,各家 ROM 對 outputX/outputY 的處理也不一致。若要穩定,建議改用 UCrop 這類第三方裁剪庫,或在 Manifest 中用 FileProvider 正確分享檔案 URI(Android 7.0 以上不允許 file:// 直接傳給其他 App)。
查了很多資料,多數寫法都是那種「上傳檔案」的複雜流程,看起來就頭大。折騰了好幾個版本都沒成功把圖片上傳上去,後來回想——HTTP 請求傳的不就是位元組嗎?那把圖片轉成位元組不就能傳過去了。
但另一個問題隨之而來:實務上我們往往不只傳一張圖,還有其他欄位,例如表單資料或使用者 ID。之前傳資料都是把 Map 或物件轉成 JSON 字串再轉 byte[],那麼現在的思路就是:
圖片 → Base64 字串 → 與其他欄位一起打包成 JSON → 字串 → byte[] → 送出。
/**
* 保存頭像
*/
public static void updateHeadImage(final String userId,
final Bitmap image,
final Handler handler) {
new Thread() {
@Override
public void run() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("userId", userId);
// Bitmap 轉字串,本質上是一個編碼過程
jsonObject.put("userImageContent", Common.Bitmap2String(image));
String content = String.valueOf(jsonObject);
String url = ConfigModel.getServerURL() + "user/updateImage";
String result = Common.httpPost(url, content);
Log.i("result", result);
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putString("result", result);
message.setData(bundle);
message.what = R.id.save_user_image_result;
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
客戶端把圖片編碼成了字串,伺服器只要解碼就能還原:
// 第一步:把資料流轉成字串
String streamIn = ReadStream.read(new BufferedInputStream(request.getInputStream()));
JSONObject object = JSONObject.fromObject(streamIn);
String userId = object.getString("userId");
String userImageContent = object.getString("userImageContent");
// 判斷是否為新圖像、產生圖像 ID 等步驟省略
String imgId = Tool.getUUID();
// 第二步:把圖像字串還原成位元組並寫檔
byte[] bitmapArray = Base64.decode(imageContent);
try {
File imageFile = new File(headImagePath);
if (!imageFile.exists()) imageFile.mkdirs();
FileOutputStream outStream = new FileOutputStream(imageFile.getPath() + "/" + imgId + ".png");
outStream.write(bitmapArray);
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
這樣就完成了一次完整的上傳。這個做法的好處是實現簡單、後端不用處理 multipart,缺點是 Base64 會讓 payload 膨脹約三分之一,圖片一大就不划算。若要傳大圖,正規做法仍是 multipart/form-data。
有了上面的思路,反向操作即可。
把 Bitmap 轉成字串,與其他欄位打包成 JSON 回傳:
// 讀取圖片並轉成字串
public static String readImage(String imgId) {
File file = new File(headImagePath + imgId + ".png");
try {
FileInputStream inputStream = new FileInputStream(file);
byte[] bitmapArray = new byte[(int) file.length()];
inputStream.read(bitmapArray);
inputStream.close();
return Base64.encode(bitmapArray);
} catch (Exception e) {
return "";
}
}
// ------------------------------------------
/**
* 查詢單一使用者
*/
@RequestMapping(value = "/user/get/{id}")
@ResponseBody
public JSONObject get(@PathVariable("id") String userId, HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
User user = userDAO.getUser(userId);
JSONObject jsonObject = new JSONObject();
jsonObject.put("user", user);
if (user.getUserImage() != null && !"".equals(user.getUserImage())) {
jsonObject.put("userImageContent", Tool.readImage(user.getUserImage()));
}
return jsonObject;
}
此時圖片資料已經是字串形式,顯示時再轉回 Bitmap 即可。
/** 圖像轉位元組 */
public static byte[] Bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
/** 圖像轉字串(Base64) */
public static String Bitmap2String(Bitmap bitmap) {
return Base64.encodeToString(Bitmap2Bytes(bitmap), Base64.DEFAULT);
}
/** 字串轉回圖像 */
public static Bitmap String2Bitmap(String st) {
try {
byte[] bitmapArray = Base64.decode(st, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
} catch (Exception e) {
return null;
}
}
BitmapFactory.Options.inSampleSize 降採樣,上傳後立刻 recycle()。以上就是整條鏈路的實作。拍照與圖片處理的部分還有優化空間,後續再補上。
Android CoordinatorLayout 與 Toolbar 滾動效果技巧
CoordinatorLayout 是 Material Design 中常見的容器布局,可用來協調子 View 之間的互動。它常與 AppBarLayout、Toolb
Android 實現 EditText 金額輸入限制
在 Android 中,EditText 可透過 inputType 限制輸入類型,但金額欄位常需要更細緻的規則,例如僅允許數字與小數點、整數部分不可為零開頭、小數最多兩
xUtils 升級到 3.0 後的用法變化:IOC、圖片、數據庫與網絡
xUtils 是最近才上手的一個框架,說實話它把不少繁瑣步驟壓縮成了一行注解,確實好用。不過 3.0 是一次大規模重構,網上能搜到的教程基本都是 2.x 的寫法,直接照抄
Service 基礎回顧:兩種啟動方式的差別一次講透
Service 是 Android 四大元件裡跟 Activity 個性最接近的一個:有自己的生命週期,創建與配置方式幾乎一致,同樣繼承自 Context,所以 getR