반응형

출처: https://black-jin0427.tistory.com/120

 

[Android,GetImage] 카메라와 갤러리에서 이미지 가져오기

안녕하세요. 블랙진입니다!! 이번에는 어마무시한 포스팅을 진행해 볼려고 합니다. 바로 '카메라와 갤러리에서 이미지 가져오기' 입니다. 단계 별로 포스팅을 진행하여 여러분 께서 쉽게 따라하고 이해할 수 있게..

black-jin0427.tistory.com

https://stackoverflow.com/questions/10296734/image-uri-to-bytesarray

 

Image Uri to bytesarray

I have currently have got two activities. One for pulling the image from the SD card and one for Bluetooth connection. I have utilized a Bundle to transfer the Uri of the image from activity 1. Now

stackoverflow.com

이미지를 SQLite 데이터베이스에 넣기 위해서는 BLOB(Binary Large OBject)이란 자료형을 사용한다.

대충 직역하면 큰 이진수 객체라는 것이다.

그래서 이를 이미지로 저장하기 위해서는 이미지를 이진수 배열로 만들어야 했다.

 

1. 먼저 갤러리에 접근하기 위한 Intent 생성 후 startActivityForResult() 메소드를 이용해 요청한다.

여기서 REQUEST_IMAGE는 내가 만든 임의의 상수값이다.

 

                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType(MediaStore.Images.Media.CONTENT_TYPE); // 갤러리 진입
                        startActivityForResult(intent, REQUEST_IMAGE);

 

2. 사진 선택 후 결과는 onActivityResult() 함수를 오버라이딩하여 처리한다.

결과코드가 RESULT_OK 일 때(이 값은 안드로이드에서 기본으로 제공해준다.),

앞에서 우리가 정의한 requestCode 값 REQUEST_IMAGE를 통해

byte 배열로의 변환 처리를 해준 후 데이터베이스에 저장한다.

 

여기서 쓰인 getContentresolver()는 갤러리의 데이터를 받아오기 위해 사용된 메소드이다.

출처: https://mainia.tistory.com/4924

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
		byte[] image = null;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_IMAGE:
                    try {
                        InputStream is = getContentResolver().openInputStream(data.getData());
                        image = dataUtil.getBytes(is);
                    } catch (IOException ie) {
                        ie.printStackTrace();
                    }
                    placeInfo.setImage(image);
                    break;
            }
        }
    }

 

getBytes() 메소드는 위에 있는 두 번째 링크의 것을 사용했다.

 

	// 이미지를 바이트 배열로 변환
    public byte[] getBytes(InputStream is) throws IOException {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int bufferSize = 1024; // 버퍼 크기
        byte[] buffer = new byte[bufferSize]; // 버퍼 배열

        int len = 0;

        // InputStream에서 읽어올 게 없을 때까지 바이트 배열에 쓴다.
        while ((len = is.read(buffer)) != -1)
            byteBuffer.write(buffer, 0, len);

        return byteBuffer.toByteArray();
    }
반응형
Posted by 애콜라이트
l

free counters