簡體   English   中英

Android 從圖庫中獲取圖像到 ImageView

[英]Android get image from gallery into ImageView

我正在嘗試將 galery 中的照片添加到ImageView但出現此錯誤:

java.lang.RuntimeException:將結果 ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/1 }} 傳遞到活動 {hotMetter. pack/hotMetter.pack.GetPhoto}: java.lang.NullPointerException

這是我的代碼:

      Intent intent = new Intent();
      intent.setType("image/*");
      intent.setAction(Intent.ACTION_GET_CONTENT);

      startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
Bitmap bitmap=null;
public void onActivityResult(int requestCode, int resultCode, Intent data)
{

    if (resultCode == Activity.RESULT_OK)
    {
        if (requestCode == SELECT_PICTURE) 
        {
             Uri selectedImageUri = data.getData();           
             selectedImagePath = getPath(selectedImageUri);             
             tv.setText(selectedImagePath);
             img.setImageURI(selectedImageUri); 
         }
    }


 public String getPath(Uri uri) 
    {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor == null) return null;
        int column_index =             cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String s=cursor.getString(column_index);
        cursor.close();
        return s;
    }

我得到selectedImagePath="mnt/sdcard/DCIM/myimage"但在img.setImageURI(selectedImageUri); 我得到了錯誤。

我還使用了Bitmap並嘗試從SetImageBitmap設置圖像,但出現相同的錯誤。

日志貓:

05-06 19:41:34.191: E/AndroidRuntime(8466): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/1 }} to activity {hotMetter.pack/hotMetter.pack.GetPhoto}: java.lang.NullPointerException
05-06 19:41:34.191: E/AndroidRuntime(8466):     at android.app.ActivityThread.deliverResults(ActivityThread.java:2532)
05-06 19:41:34.191: E/AndroidRuntime(8466):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:2574)
05-06 19:41:34.191: E/AndroidRuntime(8466):     at android.app.ActivityThread.access$2000(ActivityThread.java:117)
05-06 19:41:34.191: E/AndroidRuntime(8466):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:961)
05-06 19:41:34.191: E/AndroidRuntime(8466):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-06 19:41:34.191: E/AndroidRuntime(8466):     at android.os.Looper.loop(Looper.java:123)
05-06 19:41:34.191: E/AndroidRuntime(8466):     at android.app.ActivityThread.main(ActivityThread.java:3683)
05-06 19:41:34.191: E/AndroidRuntime(8466):     at java.lang.reflect.Method.invokeNative(Native Method)
05-06 19:41:34.191: E/AndroidRuntime(8466):     at java.lang.reflect.Method.invoke(Method.java:507)
05-06 19:41:34.191: E/AndroidRuntime(8466):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-06 19:41:34.191: E/AndroidRuntime(8466):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-06 19:41:34.191: E/AndroidRuntime(8466):     at dalvik.system.NativeStart.main(Native Method)
05-06 19:41:34.191: E/AndroidRuntime(8466): Caused by: java.lang.NullPointerException
05-06 19:41:34.191: E/AndroidRuntime(8466):     at hotMetter.pack.GetPhoto.onActivityResult(GetPhoto.java:55)
05-06 19:41:34.191: E/AndroidRuntime(8466):     at android.app.Activity.dispatchActivityResult(Activity.java:3908)
05-06 19:41:34.191: E/AndroidRuntime(8466):     at android.app.ActivityThread.deliverResults(ActivityThread.java:2528)

請指教。謝謝!

先簡單通過Intent

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

您將在onActivityResult上獲得圖片路徑:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        }
    }

完整的源代碼在這里

請嘗試以下方法:

import java.io.FileDescriptor;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class ImageGalleryDemoActivity extends Activity {


    private static int RESULT_LOAD_IMAGE = 1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

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

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }


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

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            ImageView imageView = (ImageView) findViewById(R.id.imgView);

            Bitmap bmp = null;
            try {
                bmp = getBitmapFromUri(selectedImage);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            imageView.setImageBitmap(bmp);

        }


    }



    private Bitmap getBitmapFromUri(Uri uri) throws IOException {
        ParcelFileDescriptor parcelFileDescriptor =
                getContentResolver().openFileDescriptor(uri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        parcelFileDescriptor.close();
        return image;
    }


}

@parag 的代碼很好用。 但是在加載一些大圖像時,您可能會失敗。 你應該使用;

imageView.setImageBitmap(getScaledBitmap(picturePath, 800, 800));

代替;

imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

這是我可以使用的方法。

private Bitmap getScaledBitmap(String picturePath, int width, int height) {
    BitmapFactory.Options sizeOptions = new BitmapFactory.Options();
    sizeOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(picturePath, sizeOptions);

    int inSampleSize = calculateInSampleSize(sizeOptions, width, height);

    sizeOptions.inJustDecodeBounds = false;
    sizeOptions.inSampleSize = inSampleSize;

    return BitmapFactory.decodeFile(picturePath, sizeOptions);
}

private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and
        // width
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will
        // guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    return inSampleSize;
}

這是從畫廊和裁剪屁股獲取圖像的最簡單方法

第 1 步:StartActivity 獲取結果

imageUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI);
            intent.setType("image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("scale", true);
            intent.putExtra("outputX", 256);
            intent.putExtra("outputY", 256);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, 1);

            }
    });

第二步:處理結果

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != RESULT_OK) {
        return;
    }
    if (requestCode == 1) {
        final Bundle extras = data.getExtras();
        if (extras != null) {
            //Get image
            Bitmap ProfilePic = extras.getParcelable("data");
            imageUser.setImageBitmap(ProfilePic);
            TextView t=(TextView)findViewById(R.id.textoverimage);
            t.setText("image Selected");
        }
    }


}

在調試模式下運行應用程序並在 if (requestCode == SELECT_PICTURE)上設置斷點,並在逐步執行時檢查每個變量以確保它按預期設置。 如果您在img.setImageURI(selectedImageUri);上獲得 NPE img.setImageURI(selectedImageUri); 那么imgselectedImageUri都沒有設置。

import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView)findViewById(R.id.imageView);
    }

    public void btn_gallery(View view) {

        Intent intent =new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);

        startActivityForResult(intent,100);
    }

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

        if (requestCode==100 && resultCode==RESULT_OK)
        {
            Uri uri = data.getData();
            img.setImageURI(uri);
        }
    }
}

我認為最簡單的方法是使用庫 ContentManager。 這個庫用於從設備庫、雲或相機獲取照片或視頻。 來自雲端的異步加載並修復了一些問題設備的錯誤。

通過 Gradle 下載: compile 'com.github.stfalcon:contentmanager:0.4.3'您可以在https://github.com/stfalcon-studio/ContentManager找到文檔

我認為你的 ImageView img 沒有實例化它等於 null 給編譯器; 這就是引發 NullPointerException 的原因

你有沒有調用你的活動

img = (ImageView) findViewById(R.id.my_imageview);

其中 my_imageview 是您的 ImageView 小部件的 ID!

@Parag Chauhan 解決方案運行良好,但我遇到了問題 - 一些文件管理器應用程序返回 Intent 對象“file:///...”而不是“content://...”——這是使用查詢所必需的.

對於這個問題,我有一個簡短的解決方案:

public String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {

        if("content".equals(contentUri.getScheme())) {
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        else{
            return contentUri.getPath();
        }


    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}    

基於@Parag 解決方案,

這里的部分解決方案 (@nobre) Android:從內容 URI 中獲取文件 URI?

此處的 parital 解決方案 (@Nikolay) 從 mediastore 的 URI 獲取文件名和路徑

原來的答案是你的路徑必須加入前綴像 Uri.parse("file://" + file.getPath);

這是代碼,對我有用。

Button buttonLoadImage = (Button) findViewById(R.id.button4);
    buttonLoadImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI);
            intent.setType("image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("scale", true);
            intent.putExtra("outputX", 256);
            intent.putExtra("outputY", 256);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, 1);}});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != RESULT_OK) {

        if (requestCode == RESULT_LOAD_IMAGE && data != null) {
            Uri imageUri = data.getData();
            imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageURI(imageUri);}}}

在清單文件中添加

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

將下面的代碼放在按鈕單擊事件中

Intent ImageIntent = new Intent(Intent.ACTION_PICK,               
MediaStore.Images.Media.EXTERNAL_CONTENT_URI); //implicit intent
UploadImage.this.startActivityForResult(ImageIntent,99);

將下面的代碼放在 startActivityforResult 事件中

Uri ImagePathAndName = data.getData();
imgpicture.setImageURI(ImagePathAndName);

parag-chauhandevrim 的答案是完美的,但我在沒有光標的情況下更改了 onActivityResult,它使代碼更好。

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

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
        Uri selectedImage = data.getData();
        try {
           ImageView imageView = (ImageView) findViewById(R.id.imgView);
           imageView.setImageBitmap(getScaledBitmap(selectedImage,800,800));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

private Bitmap getScaledBitmap(Uri selectedImage, int width, int height) throws FileNotFoundException {
    BitmapFactory.Options sizeOptions = new BitmapFactory.Options();
    sizeOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, sizeOptions);

    int inSampleSize = calculateInSampleSize(sizeOptions, width, height);

    sizeOptions.inJustDecodeBounds = false;
    sizeOptions.inSampleSize = inSampleSize;

    return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, sizeOptions);
}

private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        // Calculate ratios of height and width to requested one
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    return inSampleSize;
}
//try this to pick image from gallery..
    public void gotogallery(View view) { 
// onclick for gallery button
        chooseImage();
    }
// choose image from gallery
          public void chooseImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); //activity result method call
    }

    @Override
    protected void onActivityResult(int requestcode,int resultcode,Intent data ) {
        super.onActivityResult(requestcode, resultcode, data);

        if (requestcode == PICK_IMAGE_REQUEST && resultcode == RESULT_OK && data != null && data.getData() != null) {

            Uri uri = data.getData();

            try {
           Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);


                slectimageview=findViewById(R.id.imageviewimagetopdf_id);
                slectimageview.setImageBitmap(bitmap);


            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM