简体   繁体   English

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

[英]Android. How to capture image from camera and store it in server?

I am new to android.我是安卓新手。 I want to capture image using camera and store it in server.我想使用相机捕获图像并将其存储在服务器中。 Below code is to open camera and capture image.下面的代码是打开相机并捕获图像。

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

After capturing image I want that image to store in server directly.捕获图像后,我希望该图像直接存储在服务器中。 Thanks in advance.提前致谢。 Need Help.需要帮忙。 Manifest file is below:清单文件如下: 在此处输入图片说明

To store the image captured from camera, override the the activityResult callback this way:要存储从相机捕获的图像,请以这种方式覆盖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();
                }

           }
       }

EDIT : If you want the image to be saved as file into storage then manipulate it from there, you will have to proceed differently.编辑:如果您希望将图像作为文件保存到存储中,然后从那里对其进行操作,则必须以不同的方式进行。

  • First, you will have to create a file path inside xml subfolder of res folder and the file path here called file_paths.xml can be like this:首先,您必须在res文件夹的xml子文件夹中创建一个文件路径,此处称为file_paths.xml的文件路径可以是这样的:
<?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>
  • Next you will have to create a provider inside Manifest and add the file_path resource as the FILE_PROVIDER_PATH:接下来,您必须在 Manifest 中创建一个提供程序,并将 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>
  • Then inside your code(java), you will have to generate a unique path/name for the image (you can just use the following method to do so):然后在你的代码(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;
    }

The variable imageFilePath here is a member of the current class because we need it to be accessible anywhere in that class.这里的变量imageFilePath是当前类的一个成员,因为我们需要它可以在该类的任何地方访问。

You can then start the camera intent but this time you will provide the output(where data will be stored):然后您可以启动相机意图,但这次您将提供输出(将存储数据的位置):

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);

            }
  • And the last more thing will be to listen to activity result and act accordingly:最后一件事是听取活动结果并采取相应行动:
@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();
                }
           }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM