12

Tôi đang thử số hướng dẫn và mã mẫu để chụp ảnh từ thư viện hoặc máy ảnh sau đó cắt hình ảnh và tải nó lên máy chủ. Tôi đã được thực hiện mã cho rằng trong mã đó đang phải đối mặt với vài vấn đề được.Tải lên từ máy ảnh và thư viện không hoạt động bình thường trong tất cả các phiên bản

  1. Trong các thiết bị Lollipop trước khi tôi cắt hình ảnh sử dụng Ứng dụng ảnh hình ảnh là không nhận được phản ánh theo quan điểm hình ảnh nhưng nó hiển thị thông điệp như hình ảnh được lưu ..
  2. Trong điện thoại nexus cả máy ảnh và gallery không đang làm việc .
  3. 5,0 phiên bản trong vài thiết bị khi tôi cắt hình ảnh đang nhận được hình ảnh như hình dưới đây image

dưới đây là mã của tôi snippet.`

public void getPhoto() { 

     final String[] items = new String[] { "Take from camera", 
       "Select from gallery" }; 
     ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), 
       android.R.layout.select_dialog_item, items); 
     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 

     builder.setTitle("Select Image"); 
     builder.setAdapter(adapter, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int item) { // pick from 
                    // camera 
       if (item == 0) { 
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
        intent.putExtra(
          "android.intent.extras.CAMERA_FACING", 
          android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT); 
        mImageCaptureUri = Uri.fromFile(new File(Environment 
          .getExternalStorageDirectory(), "tmp_avatar_" 
          + String.valueOf(System.currentTimeMillis()) 
          + ".jpg")); 

        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, 
          mImageCaptureUri); 

        try { 
         intent.putExtra("return-data", true); 
         startActivityForResult(intent, PICK_FROM_CAMERA); 
        } catch (ActivityNotFoundException e) { 
         e.printStackTrace(); 
        } 
       } else { // pick from file 
        Intent intent = new Intent(Intent.ACTION_PICK); 
        intent.setType("image/*"); 
        // startActivityForResult(intent, SELECT_PICTURE); 
        startActivityForResult(intent, PICK_FROM_FILE); 
       } 
      } 
     }); 

     final AlertDialog dialog = builder.create(); 
     dialog.show(); 

    } 

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 

     if (resultCode != Activity.RESULT_OK) 
      return; 

     switch (requestCode) { 
     case PICK_FROM_CAMERA: 
      doCrop(); 

      break; 

     case PICK_FROM_FILE: 
      mImageCaptureUri = data.getData(); 
      doCrop(); 
      break; 

     case CROP_FROM_CAMERA: 
      Bundle extras = data.getExtras(); 
      if (extras != null) { 
       photo = extras.getParcelable("data"); 
       profile_image = encodeTobase64(photo); 
       saveType = "photo"; 
       try { 
        JSONObject obj = new JSONObject(); 
        obj.put("user_id", user_id); 
        obj.put("mode", saveType); 
        obj.put("photo", profile_image); 
        obj.put("is_profile", 1); 
        saveResponse(obj); 
       } catch (Exception e) { 
        // TODO: handle exception 
        e.printStackTrace(); 
       } 

      } 
      File f = new File(mImageCaptureUri.getPath()); 
      if (f.exists()) 
       f.delete(); 
      break; 
     } 
    } 

    private void doCrop() { 
     final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>(); 
     Intent intent = new Intent("com.android.camera.action.CROP"); 
     intent.setType("image/*"); 
     List<ResolveInfo> list = getActivity().getPackageManager() 
       .queryIntentActivities(intent, 0); 
     int size = list.size(); 
     if (size == 0) { 
      Toast.makeText(getActivity(), "Can not find image crop app", 
        Toast.LENGTH_SHORT).show(); 
      return; 
     } else { 
      intent.setData(mImageCaptureUri); 
      intent.putExtra("crop", "true"); 
      intent.putExtra("outputX", 300); 
      intent.putExtra("outputY", 300); 
      intent.putExtra("aspectX", 1); 
      intent.putExtra("aspectY", 1); 
      intent.putExtra("scale", true); 
      intent.putExtra("circleCrop", new String("")); 
      intent.putExtra("return-data", true); 
      if (size == 1) { 
       Intent i = new Intent(intent); 
       ResolveInfo res = list.get(0); 

       i.setComponent(new ComponentName(res.activityInfo.packageName, 
         res.activityInfo.name)); 
       startActivityForResult(i, CROP_FROM_CAMERA); 
      } else { 
       for (ResolveInfo res : list) { 
        final CropOption co = new CropOption(); 

        co.title = getActivity().getPackageManager() 
          .getApplicationLabel(
            res.activityInfo.applicationInfo); 
        co.icon = getActivity().getPackageManager() 
          .getApplicationIcon(
            res.activityInfo.applicationInfo); 
        co.appIntent = new Intent(intent); 
        co.appIntent 
          .setComponent(new ComponentName(
            res.activityInfo.packageName, 
            res.activityInfo.name)); 
        cropOptions.add(co); 
       } 

       CropOptionAdapter adapter = new CropOptionAdapter(
         getActivity(), cropOptions); 

       AlertDialog.Builder builder = new AlertDialog.Builder(
         getActivity()); 
       builder.setTitle("Choose Crop App"); 
       builder.setAdapter(adapter, 
         new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int item) { 
           startActivityForResult(
             cropOptions.get(item).appIntent, 
             CROP_FROM_CAMERA); 
          } 
         }); 

       builder.setOnCancelListener(new DialogInterface.OnCancelListener() { 
        @Override 
        public void onCancel(DialogInterface dialog) { 

         if (mImageCaptureUri != null) { 
          getActivity().getContentResolver().delete(
            mImageCaptureUri, null, null); 
          mImageCaptureUri = null; 
         } 
        } 
       }); 

       AlertDialog alert = builder.create(); 

       alert.show(); 
      } 
     } 
    } 

    public String encodeTobase64(Bitmap image) { 
     Bitmap immagex = image; 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
     image_Array = baos.toByteArray(); 
     String imageEncoded = Base64 
       .encodeToString(image_Array, Base64.DEFAULT); 
     return imageEncoded; 
    } 

'

nhận xét bên dưới trước khi sao chép câu hỏi này vì tôi đã được kiểm tra rất nhiều nhưng không tìm thấy bất kỳ giải pháp cho việc này, xin vui lòng cho tôi biết nếu bạn cần thêm thông tin.

+0

tôi đã xóa vấn đề 3 bằng cách xóa intent.putExtra ("circleCrop", new String ("")); từ mã – saikrupa

Trả lời

2

Tôi đang sử dụng đoạn mã này và nó đang làm việc trên tất cả các phiên bản của Android Lưu ý: Bạn có thể bỏ qua các mã thoại tùy chỉnh trong selectImage chức năng hoặc tạo hộp thoại tùy chỉnh cho nó

Thêm dòng sau vào tập tin build graddle biên dịch 'com.theartofdev.edmodo:android-image-cropper:2.1.+'

private File photoFile = null; 
    public void selectImage() { 
      final Dialog dialog = new Dialog(this, R.style.CustomDialog); 
      dialog.setContentView(R.layout.custom_dialog); 
      dialog.setCancelable(true); 
      dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); 
      final TextView camrea= (TextView) dialog.findViewById(R.id.text); 
      final TextView lib= (TextView) dialog.findViewById(R.id.text1); 
      final TextView cancel= (TextView) dialog.findViewById(R.id.text2); 
      camrea.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        dispatchTakePictureIntent() ; 
        dialog.cancel(); 
       } 
      }); 
      lib.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        if (Build.VERSION.SDK_INT < 19) { 
         Intent intent = new Intent(); 
         intent.setType("image/*"); 
         intent.setAction(Intent.ACTION_GET_CONTENT); 
         intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true); 
         startActivityForResult(Intent.createChooser(intent, "Complete action using"), 200); 
        } else { 
         Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); 
         intent.addCategory(Intent.CATEGORY_OPENABLE); 
         intent.setType("image/*"); 
         intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true); 
         startActivityForResult(intent, 300); 
        } 
        dialog.cancel(); 
       } 
      }); 
      cancel.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        dialog.cancel(); 
       } 
      }); 
      dialog.show(); 

     } 



     private void dispatchTakePictureIntent() { 
      MarshMallowPermission marshMallowPermission = new MarshMallowPermission(this); 
      if (!marshMallowPermission.checkPermissionForCamera()) { 
       marshMallowPermission.requestPermissionForCamera(); 
      } else { 
       if (!marshMallowPermission.checkPermissionForExternalStorage()) { 
        marshMallowPermission.requestPermissionForExternalStorage(); 
       } else { 
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
        // Ensure that there's a camera activity to handle the intent 
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) { 
         // Create the File where the photo should go 
         try { 
          photoFile = createImageFile(); 
         } catch (IOException ex) { 
          // Error occurred while creating the File 
         } 
         // Continue only if the File was successfully created 
         if (photoFile != null) { 
          takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); 
          //Log.d("Uri","Activity started"); 
          startActivityForResult(takePictureIntent, 100); 
         } 
        } 
       } 
      } 

      private void startCropImage(Uri crop) { 
    CropImage.activity(crop) 
      .setGuidelines(CropImageView.Guidelines.ON) 
      .setAutoZoomEnabled(true) 
      .setShowCropOverlay(true) 
      .setActivityTitle("Crop Image") 
      .start(this); 

} 

private File createImageFile() throws IOException { 
    @SuppressLint("SimpleDateFormat") 
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
    String imageFileName = "JPEG_" + timeStamp + "_"; 
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 
    return File.createTempFile(
      imageFileName,/* prefix */ 
      ".jpg",  /* suffix */ 
      storageDir /* directory */); 
} 

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (resultCode != RESULT_OK) 
      return; 

     if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { 
     final CropImage.ActivityResult result = CropImage.getActivityResult(data); 
     Log.d(TAG," : Image-URI :"+result.getUri()); 


    }else if (requestCode == 100) { 
      if("com.google.android.apps.docs.storage".equals(Uri.fromFile(photoFile).getAuthority())) 
       Toast.makeText(RegistrationActivity.this, "File Not On Device", Toast.LENGTH_SHORT).show(); 
      else { 
       startCropImage(Uri.fromFile(photoFile)); 
      } 



     } else if (requestCode == 200) { 
      mIsImageUploadUri=Uri.parse(getPathFromURI(getApplicationContext(),Uri.parse(data.getData().toString()))); 
      final Uri selectedImage = Uri.parse(getPathFromURI(getApplicationContext(),data.getData())); 
      //Log.d(TAG,"Uri"+ selectedImage.toString()); 
      if("com.google.android.apps.docs.storage".equals(selectedImage.getAuthority())) 
       Toast.makeText(RegistrationActivity.this, "File Not On Device", Toast.LENGTH_SHORT).show(); 
      else { 

       startCropImage(data.getData()); 

      } 

     }else if (requestCode == 300) { 
      final Uri originalUri = data.getData(); 
      final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 
      //noinspection ResourceType 
      getContentResolver().takePersistableUriPermission(originalUri, takeFlags); 
      Log.d(TAG,"Uri"+ originalUri.toString()); 
      if("com.google.android.apps.docs.storage".equals(originalUri.getAuthority())) 
       Toast.makeText(RegistrationActivity.this, "File Not On Device", Toast.LENGTH_SHORT).show(); 
      else { 

       startCropImage(originalUri); 
      } 
     } 
    } 
     @TargetApi(Build.VERSION_CODES.KITKAT) 
     public static String getPathFromURI(final Context context, final Uri uri) { 
      final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; 
      // DocumentProvider 
      if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { 
       // ExternalStorageProvider 
       if (isExternalStorageDocument(uri)) { 
        final String docId = DocumentsContract.getDocumentId(uri); 
        final String[] split = docId.split(":"); 
        final String type = split[0]; 
        if ("primary".equalsIgnoreCase(type)) { 
         return Environment.getExternalStorageDirectory() + "/" + split[1]; 
        } 
       } 
       // DownloadsProvider 
       else if (isDownloadsDocument(uri)) { 

        final String id = DocumentsContract.getDocumentId(uri); 
        final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); 
        return getDataColumn(context, contentUri, null, null); 
       } 
       // MediaProvider 
       else if (isMediaDocument(uri)) { 
        final String docId = DocumentsContract.getDocumentId(uri); 
        final String[] split = docId.split(":"); 
        final String type = split[0]; 
        Uri contentUri = null; 
        if ("image".equals(type)) { 
         contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; 
        } else if ("video".equals(type)) { 
         contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; 
        } else if ("audio".equals(type)) { 
         contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 
        } 
        final String selection = "_id=?"; 
        final String[] selectionArgs = new String[] { 
          split[1] 
        }; 
        return getDataColumn(context, contentUri, selection, selectionArgs); 
       } 
      } 
      // MediaStore (and general) 
      else if ("content".equalsIgnoreCase(uri.getScheme())) { 
       return getDataColumn(context, uri, null, null); 
      } 
      // File 
      else if ("file".equalsIgnoreCase(uri.getScheme())) { 
       return uri.getPath(); 
      } 
      return null; 
     } 
     public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { 
      Cursor cursor = null; 
      final String column = "_data"; 
      final String[] projection = { 
        column 
      }; 
      try { 
       cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, 
         null); 
       if (cursor != null && cursor.moveToFirst()) { 
        final int column_index = cursor.getColumnIndexOrThrow(column); 
        return cursor.getString(column_index); 
       } 
      } finally { 
       if (cursor != null) 
        cursor.close(); 
      } 
      return null; 
     } 
     public static boolean isExternalStorageDocument(Uri uri) { 
      return "com.android.externalstorage.documents".equals(uri.getAuthority()); 
     } 
     public static boolean isDownloadsDocument(Uri uri) { 
      return "com.android.providers.downloads.documents".equals(uri.getAuthority()); 
     } 
     public static boolean isMediaDocument(Uri uri) { 
      return "com.android.providers.media.documents".equals(uri.getAuthority()); 
     } 
+0

nó cũng sẽ hoạt động trong điện thoại nexus, bạn đã thử nghiệm nó – saikrupa

+0

nhưng mã của bạn không có tùy chọn cắt phải không ?. nếu có thể bạn có thể chia sẻ liên kết git để tôi có thể kiểm tra toàn bộ mã số – saikrupa

+0

không có createImageFile(); phương pháp trong mã đó bạn có thể cập nhật mà còn – saikrupa

1

tôi có cùng một vấn đề tuần trước và cuối cùng tôi giải quyết nó, đó là một chút khác biệt trong trường hợp của tôi, tôi có được một hình ảnh trong Base64 từ một máy chủ sau đó cắt nó

đây là đoạn code

byte[] decodedString = Base64.decode(imageJson, Base64.DEFAULT); 
Bitmap tmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
bitmapDecoded = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

DisplayMetrics metrics = new DisplayMetrics(); 
getWindowManager().getDefaultDisplay().getMetrics(metrics); 

int h = metrics.heightPixels; 
int w = metrics.widthPixels; 
Bitmap resized = Bitmap.createScaledBitmap(tmp, tmp.getWidth(), (int) (tmp.getHeight()*1.6), true); 
imageView.setImageBitmap(canvas.getCircleBitmap(resized, w,h)); 

imageJson được hình ảnh trong Base64 nó một String tôi biến nó trong một Bitmap, sau khi tôi nhận được kích thước của màn hình, Bitmap thay đổi kích cỡ là vào đây để có một hình ảnh vuông, vì tôi có một 16/9 hình ảnh này là có thể không hữu ích cho bạn, và cuối cùng tôi hiển thị bitmap trong một IMAGExem và cắt nó với các phương pháp vải getCircleBitmap

đây là phương pháp

public Bitmap getCircleBitmap(Bitmap bitmap,int width, int height) { 
    final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), 
      bitmap.getHeight(), Bitmap.Config.ARGB_8888); 
    final Canvas canvas = new Canvas(output); 
    final int color = Color.RED; 
    final Paint paint = new Paint(); 
    final Rect rect = new Rect((int)(bitmap.getWidth()*0.054), (int) (height*0.005), (int) (bitmap.getWidth()*0.945), (bitmap.getHeight())); 
    final RectF rectF = new RectF(rect); 

    paint.setAntiAlias(true); 
    canvas.drawARGB(0, 0, 0, 0); 
    paint.setColor(color); 
    canvas.drawOval(rectF, paint); 
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); 
    canvas.drawBitmap(bitmap, rect, rect, paint); 
    bitmap.recycle(); 

    return output; 
} 

bạn có thể thay đổi giá trị của các rect cho phù hợp với nó cho việc sử dụng của bạn Tôi tuyên bố phương pháp này trong một lớp vải mở rộng Xem, thực sự hy vọng điều này giúp bạn quá và xin lỗi cho tiếng Anh của tôi

1

tôi cũng phải đối mặt với vấn đề này ..Bây giờ nó hoạt động tốt vì tôi đang sử dụng thư viện

**compile 'com.soundcloud.android:android-crop:[email protected]'** 

công khai Uri mImageCaptureUri = null; hình ảnh

Pick từ gallery

Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
startActivityForResult(i, PICK_FROM_FILE); 

này là thêm vào phương pháp onActivityResult

//call this line after crop it 

    if(requestCode == Crop.REQUEST_CROP){ 
     handleCrop(resultCode, data); 
    } 

    case PICK_FROM_FILE: 

      mImageCaptureUri = data.getData(); 
      beginCrop(mImageCaptureUri); 
      break; 


private void beginCrop(Uri source) { 
    Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped")); 
    Crop.of(source, destination).asSquare().start(this); 
} 
private void handleCrop(int resultCode, Intent result) { 

    if (resultCode == RESULT_OK) { 
     // mImage.setImageURI(Crop.getOutput(result)); 
     Picasso.with(SettingsActivity.this).load(Crop.getOutput(result)).transform(new RoundTransform()).into(mImage); 
     mImageCaptureUri=Crop.getOutput(result); 
     getImageUri(mImageCaptureUri);  //this method uri stored to sdcard 
    } else if (resultCode == Crop.RESULT_ERROR) { 
     Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show(); 
    } 
} 
2

Nếu yêu cầu người sử dụng để chụp ảnh:

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
         if (takePictureIntent.resolveActivity(BaseActivity.this.getPackageManager()) != null) { 
          File photoFile = null; 
          try { 
           photoFile = ImageVideoUtil.createImageFile(); 
          } catch (IOException ex) { 
           ex.printStackTrace(); 
          } 
          if (photoFile != null) { 
           imagePath = Uri.fromFile(photoFile); 
           takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imagePath); 
           startActivityForResult(takePictureIntent, ApplicationConstants.REQUEST_CAMERA); 
          } 
         } 

Nếu yêu cầu người dùng chọn từ máy ảnh bạn có thể sử dụng:

Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
         startActivityForResult(intent, ApplicationConstants.REQUEST_GALLERY); 
         dialog.dismiss(); 

Và trên hoạt động của bạn gây ra bạn có thể nhận uri và sử dụng nó:

@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     BaseFragment fragment = (BaseFragment) getSupportFragmentManager().findFragmentById(R.id.fl_main); 
     if (resultCode == RESULT_OK) { 
      Bitmap bitmap = null; 
      switch (requestCode) { 
       case ApplicationConstants.REQUEST_CAMERA: 
        if (imagePath != null && fragment instanceof PhotoView) { 
         bitmap = Tools.fromGallery(this, imagePath); 
         if (bitmap != null) { 
          bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth()/2, bitmap.getHeight()/2); 
          ((PhotoView) fragment).onPhotoSet(bitmap); 
         } 
        } 
        break; 

       case ApplicationConstants.REQUEST_GALLERY: 
        Uri uri = data.getData(); 
        imagePath = uri; 
        bitmap = Tools.fromGallery(this, uri); 
        if (bitmap != null && fragment instanceof PhotoView) { 
         bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth()/2, bitmap.getHeight()/2); 
         ((PhotoView) fragment).onPhotoSet(bitmap); 
        } 
        break; 

       case ApplicationConstants.REQUEST_VIDEO: 
        if (fragment instanceof VideoView) { 
         ((VideoView) fragment).onVideoSelected(videoPath); 
        } 
        break; 
      } 

     } 
    } 

Đây Class ImageVideoUtil which'll giúp bạn cắt, quy mô, lưu và đọc các hoạt động ghi hình ảnh nền.

public class ImageVideoUtil { 

    public static void startCameraIntent(Activity activity) { 

     Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     // Ensure that there's a camera activity to handle the intent 
     if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) { 
      // Create the File where the photo should go 
      File photoFile = null; 
      try { 
       photoFile = createImageFile(); 
      } catch (IOException ex) { 
       // Error occurred while creating the File 
       ex.printStackTrace(); 
      } 
      // Continue only if the File was successfully created 
      if (photoFile != null) { 
       takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); 
       activity.startActivityForResult(takePictureIntent, ApplicationConstants.REQUEST_CAMERA); 
      } 
     } 
    } 

    public static File createImageFile() throws IOException { 
     // Create an image file name 
     String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
     String imageFileName = "SnapSense" + timeStamp + "_"; 
     File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 
     File image = File.createTempFile(imageFileName, /* prefix */ 
       ApplicationConstants.DEFAULT_IMGAE_SUFFIX, /* suffix */ 
       storageDir /* directory */ 
     ); 

     // Save a file: path for use with ACTION_VIEW intents 
     return image; 
    } 

    public static File createVideoFile() throws IOException { 
     String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
     String imageFileName = "SnapSense" + timeStamp + "_"; 
     File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES); 
     File video = File.createTempFile(imageFileName, /* prefix */ 
       ApplicationConstants.DEFAULT_VIDEO_SUFFIX, /* suffix */ 
       storageDir /* directory */ 
     ); 

     // Save a file: path for use with ACTION_VIEW intents 
     return video; 
    } 

    public static Bitmap decodeBitmap(Bitmap bmp) { 
     try { 
      ByteArrayOutputStream out = new ByteArrayOutputStream(); 
      bmp.compress(Bitmap.CompressFormat.PNG, 50, out); 
      return BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray())); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
     return bmp; 
    } 
} 

Cuối cùng đây là một số phương pháp tĩnh khác để giúp bạn:

public static Bitmap fromGallery(Context context, final Uri selectedImageUri) { 
     try { 
      Bitmap bm = MediaStore.Images.Media.getBitmap(context.getContentResolver(), selectedImageUri); 
      ExifInterface exif = new ExifInterface(selectedImageUri.getPath()); 
      int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); 
      int angle = 0; 
      switch (orientation) { 
       case ExifInterface.ORIENTATION_ROTATE_90: 
        angle = 90; 
        break; 
       case ExifInterface.ORIENTATION_ROTATE_180: 
        angle = 180; 
        break; 
       case ExifInterface.ORIENTATION_ROTATE_270: 
        angle = 270; 
        break; 
       default: 
        angle = 0; 
        break; 
      } 
      Matrix mat = new Matrix(); 
      if (angle == 0 && bm.getWidth() > bm.getHeight()) 
       mat.postRotate(90); 
      else 
       mat.postRotate(angle); 

      return Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), mat, true); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (OutOfMemoryError oom) { 
      oom.printStackTrace(); 
     } 
     return null; 
    } 

    public static String getRealPathFromURI(Activity activity, Uri contentUri) { 
     String[] proj = {MediaStore.Images.Media.DATA}; 
     Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null); 
     int column_index = cursor 
       .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
     cursor.moveToFirst(); 
     return cursor.getString(column_index); 
    } 

Tôi hy vọng mã của tôi sẽ giúp bạn. Chúc may mắn.

0

Tôi đang gặp phải sự cố tương tự trong Nexus. Tôi đã sử dụng Android Image Cropper rất nhẹ và linh hoạt.

biên dịch 'com.theartofdev.edmodo: android-image-giống chim bồ câu:. 2.2 +'

0

Mỗi phiên bản có cách riêng có để có được đường dẫn: Hãy thử phương pháp này sẽ làm việc cho tất cả các phiên bản, CNTT làm việc cho tôi :

public static String getRealPathFromURI(final Context context, final Uri uri) { 

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; 

    // DocumentProvider 
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { 
     // ExternalStorageProvider 
     if (isExternalStorageDocument(uri)) { 
      final String docId = DocumentsContract.getDocumentId(uri); 
      final String[] split = docId.split(":"); 
      final String type = split[0]; 

      if ("primary".equalsIgnoreCase(type)) { 
       return Environment.getExternalStorageDirectory() + "/" 
         + split[1]; 
      } 

      // TODO handle non-primary volumes 
     } 
     // DownloadsProvider 
     else if (isDownloadsDocument(uri)) { 

      final String id = DocumentsContract.getDocumentId(uri); 
      final Uri contentUri = ContentUris.withAppendedId(
        Uri.parse("content://downloads/public_downloads"), 
        Long.valueOf(id)); 

      return getDataColumn(context, contentUri, null, null); 
     } 
     // MediaProvider 
     else if (isMediaDocument(uri)) { 
      final String docId = DocumentsContract.getDocumentId(uri); 
      final String[] split = docId.split(":"); 
      final String type = split[0]; 

      Uri contentUri = null; 
      if ("image".equals(type)) { 
       contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; 
      } else if ("video".equals(type)) { 
       contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; 
      } else if ("audio".equals(type)) { 
       contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 
      } 

      final String selection = "_id=?"; 
      final String[] selectionArgs = new String[]{split[1]}; 

      return getDataColumn(context, contentUri, selection, 
        selectionArgs); 
     } 
    } 
    // MediaStore (and general) 
    else if ("content".equalsIgnoreCase(uri.getScheme())) { 
     return getDataColumn(context, uri, null, null); 
    } 
    // File 
    else if ("file".equalsIgnoreCase(uri.getScheme())) { 
     return uri.getPath(); 
    } 

    return null; 
} 
Các vấn đề liên quan