Как выбрать и обрезать изображение в Android?

Эй, я сейчас работаю над живыми обоями и позволяю пользователю выбрать изображение, которое будет соответствовать моим эффектам.

В настоящее время у меня есть:

Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            i.putExtra("crop", "true");
            startActivityForResult(i, 1);

И немного под этим:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if (requestCode == 1)
        if (resultCode == Activity.RESULT_OK) {
          Uri selectedImage = data.getData();
          Log.d("IMAGE SEL", "" + selectedImage);
          // TODO Do something with the select image URI
          SharedPreferences customSharedPreference = getSharedPreferences("imagePref", Activity.MODE_PRIVATE);
          SharedPreferences.Editor editor = customSharedPreference.edit();
          Log.d("HO", "" + selectedImage);
          editor.putString("imagePref", getRealPathFromURI(selectedImage));
          Log.d("IMAGE SEL", getRealPathFromURI(selectedImage));
          editor.commit();
        } 
    }

Когда мой код запускается, Logcat сообщает мне, что selectedImage имеет значение null. Если я закомментирую

i.putExtra("crop", "true"):

Logcat не дает мне исключение нулевого указателя, и я могу делать с изображением все, что хочу. Итак, в чем проблема? Кто-нибудь знает, как я могу это исправить? Спасибо за ваше время.


person Community    schedule 18.01.2010    source источник
comment
У меня тот же вопрос, и этот поток помогает, stackoverflow.com/questions/8238460/android-2-1-crop-image-fail   -  person user538565    schedule 27.11.2011
comment
другой похожий поток: stackoverflow.com/questions/12758425/   -  person hcpl    schedule 17.04.2013


Ответы (3)


Я также столкнулся с этой проблемой. Вы можете попробовать этот код. У меня работает нормально

private static final String TEMP_PHOTO_FILE = "temporary_holder.jpg";  

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, REQ_CODE_PICK_IMAGE);

private Uri getTempUri() {
    return Uri.fromFile(getTempFile());
}

private File getTempFile() {

    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

        File file = new File(Environment.getExternalStorageDirectory(),TEMP_PHOTO_FILE);
        try {
            file.createNewFile();
        } catch (IOException e) {}

        return file;
    } else {

        return null;
    }
}

protected void onActivityResult(int requestCode, int resultCode,
        Intent imageReturnedIntent) {

    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch (requestCode) {
        case REQ_CODE_PICK_IMAGE:
            if (resultCode == RESULT_OK) {  
                if (imageReturnedIntent!=null) {

                    File tempFile = getTempFile();

                    String filePath= Environment.getExternalStorageDirectory()
                        +"/"+TEMP_PHOTO_FILE;
                    System.out.println("path "+filePath);


                    Bitmap selectedImage =  BitmapFactory.decodeFile(filePath);
                    _image = (ImageView) findViewById(R.id.image);
                    _image.setImageBitmap(selectedImage );

                    if (tempFile.exists()) tempFile.delete();
                }
            }
    }       
}
person jennifer    schedule 17.03.2011
comment
Просто помните, что если вы хотите удалить файлы, вам, вероятно, потребуется добавить это разрешение в свой манифест: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> - person HGPB; 18.02.2013
comment
@ Харальдо. В андроиде 4.1 не проверял. я проверю и обновлю - person jennifer; 25.02.2013
comment
@jennifer Как насчет того, чтобы сделать то же самое для Camera Capture, есть идеи? - person Herry; 30.06.2014
comment
Намерение getCameraImage = новое намерение (android.media.action.IMAGE_CAPTURE); - person e-info128; 01.02.2015
comment
я могу найти путь, используя ваш код... но я не могу показать изображение - person H Raval; 10.03.2016

Вам не нужен временный файл:

protected static final int REQ_CODE_PICK_IMAGE = 1;



Intent photoPickerIntent = new Intent(Intent.ACTION_PICK,
    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    photoPickerIntent.setType("image/*");
    photoPickerIntent.putExtra("crop", "true");
    photoPickerIntent.putExtra("return-data", true);
    photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    startActivityForResult(photoPickerIntent, REQ_CODE_PICK_IMAGE);


protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {

        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

        switch (requestCode) {
            case REQ_CODE_PICK_IMAGE:
                if (resultCode == RESULT_OK) {  
                    if (imageReturnedIntent!=null) {
                        Bundle extras = imageReturnedIntent.getExtras();
                        Bitmap selectedBitmap = extras.getParcelable("data");
                        imageR = (ImageView) findViewById(R.id.image);
                        imageR.setImageBitmap(selectedBitmap);
                    }
                }
        }       
}
person toni    schedule 10.04.2015
comment
Вы спасли мой день! На 4.3- - работало нормально. на 4.4+ можно использовать обычный вариант: imageStream = getContentResolver().openInputStream(imageuri); Растровое изображение bmap = BitmapFactory.decodeStream(imageStream); - person kaftanati; 21.04.2015
comment
Это не работает, когда выбрано приложение Google Фото для выбора изображения. - person Gaurav; 20.05.2017
comment
Исключение нулевого указателя возникает при выборе фотографий из приложения Google Photos. - person Senthilvel S; 22.01.2019
comment
Ничего не происходит после выбора, обрезки и нажатия значка ОК/галочки. Он застрял на экране кадрирования. Любая идея ? - person Yusril Maulidan Raji; 18.09.2019

Этот код хорош для "новичков" ^^

private Bitmap FixBitmap;
Bitmap thePicBitmap;
String ImagePath = "image_path";
String ImagePath_1;
private static final String TEMP_PHOTO_FILE = "temporary_holder.jpg";
private static final int REQ_CODE_PICK_IMAGE = 0;




@Override
        public void onClick(View view) {
            try {




            //intent = new Intent();
            // intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
             Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            //intent.setAction(Intent.ACTION_GET_CONTENT);
             photoPickerIntent.setType("image/*");
             photoPickerIntent.putExtra("crop", "true");
             photoPickerIntent.putExtra("scale", true);
             photoPickerIntent.putExtra("aspectX", 1);
             photoPickerIntent.putExtra("aspectY", 1);
             // indicate output X and Y
             photoPickerIntent.putExtra("outputX", 150);
             photoPickerIntent.putExtra("outputY", 100);


             photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
             photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
             startActivityForResult(photoPickerIntent, REQ_CODE_PICK_IMAGE);




            } catch (Exception e) {
               // Toast.makeText(getApplicationContext(), R.string.imageException, Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
                Toast toast = Toast.makeText(Upload_image_text.this, "This device doesn't support the crop action!",
                        Toast.LENGTH_SHORT);
                toast.show();
            }




        }

        private Uri getTempUri() {
            return Uri.fromFile(getTempFile());
            }

        private File getTempFile() {
            if (isSDCARDMounted()) {

            File f = new File(Environment.getExternalStorageDirectory(),TEMP_PHOTO_FILE);
            try {
            f.createNewFile();
            } catch (IOException e) {

            }
            return f;
            } else {
            return null;
            }
            }

        private boolean isSDCARDMounted(){
            String status = Environment.getExternalStorageState();
            if (status.equals(Environment.MEDIA_MOUNTED))
            return true;
            return false;
            }
    });

=======================

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {

    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);


    switch (requestCode) {
    case REQ_CODE_PICK_IMAGE:
        if (resultCode == RESULT_OK) {  
          if (imageReturnedIntent!=null){



          //     File tempFile = getTempFile();

              ImagePath_1 = Environment.getExternalStorageDirectory()
            + "/temporary_holder.jpg";
              System.out.println("path "+ImagePath_1);


              FixBitmap =  BitmapFactory.decodeFile(ImagePath_1);
              ShowSelectedImage = (ImageView)findViewById(R.id.imageView);
              ShowSelectedImage.setImageBitmap(FixBitmap);



          }
        }
    }
}

===============================

@Override
        protected String doInBackground(Void... params) {


            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 1;
            //options.outWidth = 50;
            //options.outHeight = 50;
            FixBitmap = BitmapFactory.decodeFile(ImagePath_1, options);
            //FixBitmap = BitmapFactory.decodeResource(getResources(), R.id.imageView);

           byteArrayOutputStream = new ByteArrayOutputStream();
           FixBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); //compress to 50% of original image quality
           byteArray = byteArrayOutputStream.toByteArray();

           ConvertImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
person Alobaidi    schedule 18.07.2017