[안드로이드] 디바이스의 사진을 가져와 랜덤하게 이미지뷰에 출력

조회수 2927회
public class MainActivity extends AppCompatActivity {

    ImageView imageview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageview = (ImageView)findViewById(R.id.imageview);

        Uri uri = pickRandomImage();
        ArrayList<Uri> allImageUri;
        allImageUri = getAllImage();
        int total = allImageUri.size();
        int randomIndex = (int)(Math.random()*total);

        Uri randomUri = allImageUri.get(randomIndex);

        try {
            Bitmap bm = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            imageview.setImageBitmap(bm);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "파일 없음", 0).show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "오류", 0).show();
        }
    }

    ArrayList<Uri> getAllImage() {
        String[] projection = {MediaStore.Images.Media.DATA};

        Cursor c = getApplicationContext().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection,
                null,
                null,
                null);

        ArrayList<Uri> result = new ArrayList<>(c.getCount());
        int dataColumnIndex = c.getColumnIndex(projection[0]);

        if (c == null) {
            Toast.makeText(getApplicationContext(), "사진이 없습니다.", 0);
        } else if (c.moveToFirst()) {
            do {
                String filepath = c.getString(dataColumnIndex);
                Uri imageUri = Uri.parse(filepath);
                result.add(imageUri);
            }while(c.moveToNext());
        }else{
            Toast.makeText(getApplicationContext(), "커서가 비었습니다", 0);
        }
        c.close();
        return result;
    }

디바이스의 사진의 uri를 모두 가져와 배열로 저장하고 난수를 발생시켜 그 난수를 이용해 랜덤한 uri 를 가져와 비트맵으로 이미지뷰에 출력하고자 했는데 사진이 나오지 않습니다. 토스트 메시지를 확인하면 파일없음 이라 나와 비트맵으로 이미지뷰에 출력 하는데에 문제가 있는거 같은데 어떻게 구현하면좋을까요

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • MediaStore.Images.Media.getBitmap()의 두번째 파라미터인 uri는 파일 스킴을 넘겨줘야 됩니다. 다음과 같이 코드를 변경해보세요.

    MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.parse("file://" + uri));
    

    또는

    MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(new File(uri)));
    
    • (•́ ✖ •̀)
      알 수 없는 사용자
    • 감사합니다. 저거 하나 해결못해서 계속 쩔쩔 매고있엇네요 그런데 이번엔 outofmemory 문제가 생기네요 ㅎㅎㅎㅎㅎㅎ 알 수 없는 사용자 2016.11.9 17:21

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)