一、调用相机拍照
在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 中拍照上传的基本实现方式,帮助您更好地开发移动应用。