无法从Android上的相机上传图像

时间:2017-09-21 05:07:01

标签: android android-camera

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

6 个答案:

答案 0 :(得分:3)

请通过以下代码

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

答案 1 :(得分:0)

试试这个,它可能会有所帮助

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 :(得分:0)

@angular/cli: 1.2.0
node: 8.0.0
os: linux x64
@angular/animations: 4.3.6
@angular/common: 4.3.6
@angular/compiler: 4.3.6
@angular/core: 4.3.6
@angular/forms: 4.3.6
@angular/http: 4.3.6
@angular/platform-browser: 4.3.6
@angular/platform-browser-dynamic: 4.3.6
@angular/router: 4.3.6
@angular/cli: 1.2.0
@angular/compiler-cli: 4.3.6
@angular/language-service: 4.3.6

答案 3 :(得分:0)

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

首先,请在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 :(得分:0)

试一试!

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

答案 5 :(得分:0)

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

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