【问题标题】:Not able to upload image from camera in android无法从android中的相机上传图像
【发布时间】:2017-09-21 05:07:00
【问题描述】:

我正在开发一个应用程序,我想从图库或相机中获取图像,然后使用 multipart 将其发送到服务器。我可以将图片从画廊发送到服务器,但是当我尝试从相机发送图像时,它显示我失败了。

// 相同的代码

//打开相机的代码

     private void cameraIntent() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, REQUEST_CAMERA);

}

//关于活动结果

  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
       if (requestCode == REQUEST_CAMERA) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
            File destination = new File(Environment.getExternalStorageDirectory(),
                    System.currentTimeMillis() + ".jpg");

            Log.d("TAG", "onActivityResult: "+Uri.fromFile(destination));

            filePath = destination.toString();
            if (filePath != null) {

                try {
                    execMultipartPost();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getActivity(), "Image not capturd!", Toast.LENGTH_LONG).show();
            }
        }

// 发送到服务器代码

  private void execMultipartPost() throws Exception {

    File file = new File(filePath);
    String contentType = file.toURL().openConnection().getContentType();

    Log.d("TAG", "file new path: " + file.getPath());
    Log.d("TAG", "contentType: " + contentType);


    RequestBody fileBody = RequestBody.create(MediaType.parse(contentType), file);

    final String filename = "file_" + System.currentTimeMillis() / 1000L;



    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)


            .addFormDataPart("date", "21-09-2017")
            .addFormDataPart("time", "11.56")
            .addFormDataPart("description", "hello")
            .addFormDataPart("image", filename + ".jpg", fileBody)


            .build();

    Log.d("TAG", "execMultipartPost: "+requestBody);

    okhttp3.Request request = new okhttp3.Request.Builder()
            .url("http://myexample/api/user/lets_send")
            .post(requestBody)
            .build();

    OkHttpClient okHttpClient = new OkHttpClient();


    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, final IOException e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Toast.makeText(getActivity(), "nah", Toast.LENGTH_SHORT).show();
                }
            });
        }


        @Override
        public void onResponse(Call call, final okhttp3.Response response) throws IOException {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {

                        Log.d("TAG", "response of image: " + response.body().string());

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    });
}

【问题讨论】:

  • 能否在此处添加您的错误日志
  • 使用断点将帮助您更好地识别问题。

标签: android android-camera


【解决方案1】:

试试这个,可能会有帮助

Intent takePhotoIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 Date date = new Date();
        String timeStamp = new SimpleDateFormat(pictureNameDateFormat, Locale.US).format(date.getTime());
    File fileDirectory = new File(Environment.getExternalStorageDirectory() + "/Pictures");


if (fileDirectory.exists()) {
                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(
                        new File(Environment.getExternalStorageDirectory() + "/Pictures/picture_"+ timeStamp + ".png")));
                takePhotoIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                takePhotoIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                if (takePhotoIntent.resolveActivity(activity.getPackageManager()) != null) {
                    activity.startActivityForResult(takeVideoIntent, captureVideoActivityRequestCode);
                }
            }

【讨论】:

    【解决方案2】:
    private void onCaptureImageResult(Intent data) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File destination = new File(Environment.getExternalStorageDirectory(),
                System.currentTimeMillis() + ".jpg");
        FileOutputStream fo;
        try {
            destination.createNewFile();
            fo = new FileOutputStream(destination);
            fo.write(bytes.toByteArray());
            fo.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
      Log.e("path",Environment.getExternalStorageDirectory(),
                System.currentTimeMillis() + ".jpg");
    
    
    }
    

    【讨论】:

      【解决方案3】:

      请使用以下代码通过相机捕获图像并从图库中选择图像,您也可以裁剪。

      首先请在你的build.gradle中添加这个依赖

      compile 'com.theartofdev.edmodo:android-image-cropper:2.3.+'
      

      请在您的活动中添加此代码:

      uploadPic.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {               
                      onSelectImageClick(view);
                  }
              });
      
       /**
           * Start pick image activity with chooser.
           */
          public void onSelectImageClick(View view) {
              if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      
                  if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.CAMERA) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                      ActivityCompat.requestPermissions(AccountSettingActivity.this, new String[]{android.Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_REQUEST_CAMERA);
                  } else if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.CAMERA) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                      CropImage.startPickImageActivity(this);
                  }
              }else {
                  CropImage.startPickImageActivity(this);
              }
          }
      
      @Override
          @SuppressLint("NewApi")
          protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      
              // handle result of pick image chooser
              if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
                  Uri imageUri = CropImage.getPickImageResultUri(this, data);
                  startCropImageActivity(imageUri);
              }
      
              // handle result of CropImageActivity
              if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
                  CropImage.ActivityResult result = CropImage.getActivityResult(data);
                  if (resultCode == RESULT_OK) {
                      fileUri = result.getUri();
                      userImage.setImageURI(result.getUri());
                      Toast.makeText(this, "Cropping successful, Sample: " + result.getSampleSize(), Toast.LENGTH_LONG).show();
                  } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                      Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
                  }
              }
          }
      
          @Override
          public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
              if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
                  CropImage.startPickImageActivity(this);
              } else {
                  Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
              }
          }
      
          /**
           * Start crop image activity for the given image.
           */
          private void startCropImageActivity(Uri imageUri) {
              CropImage.activity(imageUri)
                      .setGuidelines(CropImageView.Guidelines.ON)
                      .setMultiTouchEnabled(true)
                      .start(this);
          }
      

      【讨论】:

        【解决方案4】:
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
        

        请在清单中添加这些权限并要求运行时权限,这可能会解决您的问题,您的编码是正确的,在添加权限后对我来说完美。

        【讨论】:

          【解决方案5】:

          请看下面的代码

           try {
              if (imageUri != null) {
                  photo = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri));
              } else {
                  photo = (Bitmap) data.getExtras().get("data");
              }
              Uri tempUri = CommonData.getImageUri(getContext(), photo);
              uri = tempUri.toString();
              String path = CommonData.convertImageUriToFile(tempUri, getActivity());
              //                new PreprocessImagesTask().execute(path);
              showLoader();
              new ProcessingImage(this).execute(path);
          
          } catch (Exception e) {
              e.printStackTrace();
          
          }
          
          public static Uri getImageUri(Context inContext, Bitmap inImage) {
              ByteArrayOutputStream bytes = new ByteArrayOutputStream();
              inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
              String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
              return Uri.parse(path);
          }
          
          public static String convertImageUriToFile(Uri imageUri, Activity activity) {
              String imgPath = "";
              String Path;
              try {
                  Cursor cursor = null;
                  int imageID = 0;
          
                  try {
                      /* ********** Which columns values want to get ****** */
                      String[] proj = {
                              MediaStore.Images.Media.DATA,
                              MediaStore.Images.Media._ID,
                              MediaStore.Images.Thumbnails._ID,
                              MediaStore.Images.ImageColumns.ORIENTATION
                      };
          
                      cursor = activity.getContentResolver().query(
          
                              imageUri,   // Get data for specific image URI
                              proj,       // Which columns to return
                              null,       // WHERE clause; which rows to return (all rows)
                              null,       // WHERE clause selection arguments (none)
                              null        // Order-by clause (ascending by name)
          
                      );
          
                      int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                     int size = cursor.getCount();
          
                      /* ******  If size is 0, there are no images on the SD Card. **** */
          
                      if (size == 0) {
                          //                imageDetails.setText("No Image");
                      } else {
          
                          int thumbID = 0;
                          if (cursor.moveToFirst()) {
                              Path = cursor.getString(file_ColumnIndex);
                              //String orientation =  cursor.getString(orientation_ColumnIndex);
                              String CapturedImageDetails = " CapturedImageDetails : \n\n"
                                      + " ImageID :" + imageID + "\n"
                                      + " ThumbID :" + thumbID + "\n"
                                      + " Path :" + Path + "\n";
                              showLog("CapturedImageDetails", CapturedImageDetails);
                              imgPath = Path;
                              // Show Captured Image detail on view
                              //                    imageDetails.setText(CapturedImageDetails);
          
                          }
                      }
                  } finally {
                      if (cursor != null) {
                          cursor.close();
                      }
                  }
          
                  return "" + imgPath;
              } catch (IllegalArgumentException e) {
                  e.printStackTrace();
                  return "";
              }
          }
          

          【讨论】:

            【解决方案6】:

            试一试!

            private static final int REQUEST_IMAGE = 100;   
            private static final String TAG = "MainActivity";
            TextView imgPath;
            ImageView picture;
            File destination;
            String imagePath;
            
            //onCreate
            
                private void cameraIntent() {  
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
                    startActivityForResult(intent, REQUEST_IMAGE); 
                }
            
            }
            
            @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                if( requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK ){
                    try {
                        FileInputStream in = new FileInputStream(destination);
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 10;
                        imagePath = destination.getAbsolutePath();//get your path
                        imgPath.setText(imagePath);
                        Bitmap bmp = BitmapFactory.decodeStream(in, null, options);
                        picture.setImageBitmap(bmp);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
            
                }
                else{
                    imgPath.setText("Request cancelled");
                }
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-01-05
              • 1970-01-01
              相关资源
              最近更新 更多