安卓如何从相机捕获图像并将其存储在服务器中?

时间:2018-12-06 05:51:36

标签: android retrofit2

我是android新手。我想使用相机捕获图像并将其存储在服务器中。下面的代码是打开相机并捕获图像。

 private void openCamera() {
    requestPermissions(TYPE_IMAGE);
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT,contentURI);
    startActivityForResult(intent, CAMERA);
}

捕获图像后,我希望该图像直接存储在服务器中。提前致谢。需要帮忙。 清单文件如下: enter image description here

1 个答案:

答案 0 :(得分:0)

要存储从相机捕获的图像,请通过以下方式覆盖activityResult回调:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode==RESULT_OK && requestCode==CAMERA_CODE)
        {
                try {

                    Bundle extras = data.getExtras();
                    Bitmap imageBitmap = (Bitmap) extras.get("data");

                    //if you want to encode the image into base64
                    if (imageBitmap!=null) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
           String encodeImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);

            //You can send your image to server
                } catch (Exception e) {
                    e.printStackTrace();
                }

           }
       }

编辑:如果您希望将图像作为文件保存到存储中,然后从那里进行操作,则必须以不同的方式进行。

  • 首先,您将必须在 res 文件夹的 xml 子文件夹中创建一个文件路径,此处名为file_paths.xml的文件路径可以像这样:< / li>
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images"
        path="Android/data/YOUR_PACKAGE/files/Pictures" />
</paths>
  • 接下来,您将不得不在清单中创建一个提供程序,并将file_path资源添加为FILE_PROVIDER_PATH:
<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
  • 然后在代码(java)中,必须为图像生成唯一的路径/名称(您可以使用以下方法来做到这一点):
  private File createImageFile() throws IOException {
        String timeStamp =
                new SimpleDateFormat("yyyyMMdd_HHmmss",
                        Locale.getDefault()).format(new Date());
        String imageFileName = "IMG_" + timeStamp + "_";
        File storageDir =
                getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        imageFilePath = image.getAbsolutePath();
        return image;
    }

这里的变量imageFilePath是当前类的成员,因为我们需要该变量在该类中的任何位置都可以访问。

然后您可以启动摄像机的意图,但是这次您将提供输出(将在其中存储数据):

Intent picture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (picture.resolveActivity(getPackageManager()) != null) {

            File photo = null;
                      try {


                          photo = createImageFile();

                     } catch (IOException ex) {

                  }

                 if (photo != null) {
                    Uri photoURI = FileProvider.getUriForFile(this,
                           "YOUR_PACKAGE_NAME.provider",
                        photo);

              picture.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(picture, CAMERA_CODE);

            }
  • 最后一件事是听取活动结果并采取相应行动:
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode==RESULT_OK)
        {

                try {
                    Bundle extras = data.getExtras();
                    //our imageFilePath that contains the absolute path to the created file 
                    File file = new File(imageFilePath);
                    Bitmap imageBitmap = MediaStore.Images.Media
                            .getBitmap(getContentResolver(), Uri.fromFile(file));
                  //do whatever else after
                } catch (Exception e) {
                    e.printStackTrace();
                }
           }
    }