无法在android中从相机上载图像

无法在android中从相机上载图像,android,android-camera,Android,Android Camera,我正在开发一个应用程序,在这个应用程序中,我想从画廊或相机中获取图像,然后使用multipart将其发送到服务器。我可以将图片从图库发送到服务器,但当我尝试从相机发送图片时,它显示我失败了 //代码相同 //打开摄影机的代码 private void cameraIntent() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, RE

我正在开发一个应用程序,在这个应用程序中,我想从画廊或相机中获取图像,然后使用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();
                    }
                }
            });
        }
    });
}

请输入以下代码

 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 "";
    }
}
试试这个,可能会有帮助

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

请使用以下代码通过相机拍摄图像,并从图库中拾取图像,您也可以进行裁剪

首先,请在您的
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);
    }
试试看

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


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

您可以在此处添加错误日志吗?使用断点将帮助您更好地识别问题。
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");
    }
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>