一、調用相機拍照
在Android中,我們可以使用Intent調用系統相機拍照。以下是一個調用拍照界面的示例代碼:
// 打開系統相機
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// 創建一個保存照片的文件路徑
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.e(TAG, ex.getMessage());
}
if (photoFile != null) {
// 把文件路徑裝進 Intent
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
// 創建保存照片的文件路徑
private File createImageFile() throws IOException {
// 以當前時間生成文件名
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* 前綴 */
".jpg", /* 後綴 */
storageDir /* 目錄 */
);
// 保存文件路徑以便之後調用相機
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
二、將拍攝的照片上傳到服務器
在拍照完成後,我們需要將照片上傳到服務器。以下是一個上傳照片的示例代碼:
// 使用 OkHttp 上傳圖片到服務器
public void uploadImage(File imageFile) throws IOException {
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM) // 設置為表單類型
.addFormDataPart("file", imageFile.getName(),
RequestBody.create(MediaType.parse("image/*"), imageFile))
.build();
Request request = new Request.Builder()
.url("https://example.com/upload_image")
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Log.d(TAG, response.body().string());
}
三、顯示拍攝的照片
在拍照完成並上傳照片後,我們希望能夠顯示拍攝的照片。以下是一個顯示照片的示例代碼:
// 顯示拍照後的圖片
private void setPic() {
// 獲取 ImageView 的尺寸
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// 獲取圖片的尺寸
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// 根據 ImageView 的尺寸計算縮放比例
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// 解碼圖片文件並縮放
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mImageView.setImageBitmap(bitmap);
}
四、權限申請
在 Android 6.0 及以上版本中,需要在運行時申請拍照和文件存儲的權限。以下是一個權限申請的示例代碼:
// 檢查權限並申請
private void checkPermissions() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE_PERMISSION);
}
}
// 處理權限申請結果
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
takePicture();
}
} else if (requestCode == REQUEST_WRITE_STORAGE_PERMISSION) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
checkPermissions();
}
}
}
五、錯誤處理
在開發中,我們需要確保錯誤處理機制的健全。以下是一個上傳照片時的錯誤處理的示例代碼:
// 使用 OkHttp 上傳圖片到服務器
public void uploadImage(File imageFile) throws IOException {
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM) // 設置為表單類型
.addFormDataPart("file", imageFile.getName(),
RequestBody.create(MediaType.parse("image/*"), imageFile))
.build();
Request request = new Request.Builder()
.url("https://example.com/upload_image")
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Log.d(TAG, response.body().string());
} catch (ConnectException e) {
Log.e(TAG, "Failed to connect to server.");
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
}
六、總結
本文詳細介紹了如何在 Android 中實現拍照上傳功能,並分別從調用相機拍照、上傳照片、顯示照片、權限申請和錯誤處理等方面進行了詳細闡述。通過本文,您可以掌握 Android 中拍照上傳的基本實現方式,幫助您更好地開發移動應用。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/159803.html
微信掃一掃
支付寶掃一掃