如何在安卓设备上选择和裁剪图片?

31

嗨,我目前正在开发一个动态壁纸应用程序,并允许用户选择一张图片作为我的效果背景。

目前我已经有:

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没有给我空指针异常,而且我可以按照我的意愿操作图片。那么问题出在哪里呢?有人知道如何解决吗?谢谢你们的时间。


我有同样的问题,这个帖子很有帮助,http://stackoverflow.com/questions/8238460/android-2-1-crop-image-fail - user538565
另一个类似的线程:https://dev59.com/LWnWa4cB1Zd3GeqPy0Yr - hcpl
3个回答

47

我也遇到了这个问题。你可以尝试使用这段代码。它对我来说很好用。

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

2
只需记住,如果您想要删除文件,则可能需要将此权限添加到您的清单中:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> - HGPB
@Haraldo。我没有在Android 4.1上检查过它。我会检查并更新。 - jennifer
1
@jennifer 你有没有关于相机捕获的同样想法? - Herry
意图获取相机图片 = 新意图("android.media.action.IMAGE_CAPTURE"); - e-info128
我可以使用你的代码找到路径...但是我无法显示图像。 - H Raval

7

您无需使用临时文件:

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

1
你救了我的一天!在4.3上运行良好。在4.4+上可以使用常规变量: imageStream = getContentResolver().openInputStream(imageuri); Bitmap bmap = BitmapFactory.decodeStream(imageStream); - kaftanati
当选择Google相册应用程序选择图像时,此功能无法正常工作。 - Gaurav
从Google相册应用程序中选择照片时会出现空指针异常。 - Senthilvel S
在选择、裁剪并点击“确定/勾选”图标后,什么也没有发生。它停留在裁剪屏幕上。有任何想法吗? - Yusril Maulidan Raji

0

这段代码适合“初学者”^^

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接