简体   繁体   中英

Not able to upload image from camera in android

I am working on an app in which I want to get image from gallery or camera and then send it to server using multipart. I am able to send picture from gallery to server but when I tried to send image from camera it shows me failure.

// code for the same

// code fro open camera

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

}

// on activity result

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

// send to server code

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

Please go trough the following code

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

Try This, it may help

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


}

Please use below code to capture image by camera and for pick image from gallery and you can crop also.

First of all please add this dependency in your build.gradle

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

In your Activity please add this code :

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

Give a try!

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"/>

in manifest please add these permissions and ask for run time permissions also ,this may solve your problem ,Your coding is correct those works for me perfectly after adding permission.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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