2016-09-22 3 views
1

갤러리에서 이미지를 가져 오려고합니다. 이미지를 비트 맵으로 제공합니다. 내 이미지 파일을 .jpg 파일로 저장하여 데이터베이스에 파일 이름을 저장할 수 있습니다.갤러리에서 .jpg 파일 형식으로 이미지를 가져 오는 방법은 무엇입니까?

이 나는이 자습서를 따랐다 :

http://www.theappguruz.com/blog/android-take-photo-camera-gallery-code-sample

갤러리 이미지 선택 코드 :

@SuppressWarnings("deprecation") 
private void onSelectFromGalleryResult(Intent data) { 

    Bitmap bm=null; 
    if (data != null) { 
     try { 
      bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    Uri selectedImage = data.getData(); 

    String[] filePath = {MediaStore.Images.Media.DATA}; 

    Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null); 


    c.moveToFirst(); 

    int columnIndex = c.getColumnIndex(filePath[0]); 

    String picturePath = c.getString(columnIndex); 

    c.close(); 
    File file = new File(picturePath);// error line 

    mProfileImage = file; 

    profile_image.setImageBitmap(bm); 
} 

나는이 시도. 하지만 파일에 null 포인터가 나타납니다.

예외 :

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference 

는 또한 나는이 새로 생성 된 파일을 외부 저장 장치에 저장하고 싶지 않아요. 이것은 임시 파일이어야합니다. 어떻게해야합니까?

+0

확인하십시오. http://stackoverflow.com/questions/5383797/open-an-image-using-uri-in-androids-default-gallery-image-viwer – Shailesh

답변

1

좋은 소식은 당신이 생각하는 것보다 수행에 많은 가까운 것입니다 .. 감사합니다! 경우 bm != null이 시점에서

Bitmap bm=null; 
if (data != null) { 
    try { 
     bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData()); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

는, 당신은 비트 맵 객체가 있습니다. 비트 맵은 갈 준비가 된 안드로이드의 일반적인 이미지 객체입니다. 이미 실제로 .jpg 형식으로되어 있으므로 파일에 써야합니다.

File outputDir = context.getCacheDir(); // Activity context 
File outputFile = File.createTempFile("prefix", "extension", outputDir); // follow the API for createTempFile 

에 관계없이,이 파일에 Bitmap를 작성하는 매우 쉬운이 시점에서 : 당신은 그래서 나는 이런 식으로 뭔가를 할 거라고, 임시 파일에 기록하고 싶다.

ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
bm.compress(Bitmap.CompressFormat.JPEG, 100, stream); //replace 100 with desired quality percentage. 
byte[] byteArray = stream.toByteArray(); 

이제 바이트 배열이 생겼습니다. 그 파일을 당신에게 파일로 남겨 두겠습니다. 멀리 갈 임시 파일을 원하는 경우

, 추가 정보를 원하시면 여기를 참조하십시오 https://developer.android.com/reference/java/io/File.html#deleteOnExit()

Bitmap bm=null; 
if (data != null) { 
    try { 
     bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData()); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
if (bm != null) { // sanity check 
    File outputDir = context.getCacheDir(); // Activity context 
    File outputFile = File.createTempFile("image", "jpg", outputDir); // follow the API for createTempFile 

    FileOutputStream stream = new FileOutputStream (outputFile, false); // Add false here so we don't append an image to another image. That would be weird. 
    // This line actually writes a bitmap to the stream. If you use a ByteArrayOutputStream, you end up with a byte array. If you use a FileOutputStream, you end up with a file. 
    bm.compress(Bitmap.CompressFormat.JPEG, 100, stream); 
    stream.close(); // cleanup 
} 

나는 희망이 도움이!

+0

임시 파일을 만드는 답을 시도했습니다. 그러나 파일을 변환하는 동안 추가로 오류가 발생합니다. 편집 된 질문을 확인해주십시오. ? @Eric – Sid

+0

@Sid 미안하지만, 당신이 나를 오해 한 것 같아요. 일단 비트 맵을 얻으면 바이트 배열로 변환하려고합니다 : 'ByteArrayOutputStream stream = new ByteArrayOutputStream(); bm.compress (Bitmap.CompressFormat.JPEG, 100, 스트림); // 원하는 품질 백분율로 100을 대체하십시오. byte [] byteArray = stream.toByteArray(); ' 일단 바이트 배열로 변환하면 그 배열을 파일에 씁니다. 귀하의 코드에서, 당신이 그렇게하는 것처럼 보이지 않습니다. – Eric

0

picturePath이 null 인 것 같습니다. 그래서 이미지를 변환 할 수 없습니다. 선택한 이미지의 경로를 얻기 위해이 코드 조각을 추가하십시오 : 그 후

private String getRealPathFromURI(Uri uri) { 
    String[] projection = { MediaStore.Images.Media.DATA }; 
    @SuppressWarnings("deprecation") 
    Cursor cursor = managedQuery(uri, projection, null, null, null); 
    int column_index = cursor 
     .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
    cursor.moveToFirst(); 
    return cursor.getString(column_index); 
} 

을, 당신은 당신의 onSelectFromGalleryResult을 수정해야합니다. 줄 String[] filePath = {MediaStore.Images.Media.DATA}; 등을 제거/비활성화하고 아래에서 바꾸십시오.

Uri selectedImageUri = Uri.parse(selectedImage); 
String photoPath = getRealPathFromURI(selectedImageUri); 
mProfileImage = new File(photoPath); 

//check if you get something like this - file:///mnt/sdcard/yourselectedimage.png 
Log.i("FilePath", mProfileImage.getAbsolutePath) 
if(mProfileImage.isExist()){ 
    //Check if the file is exist. 
    //Do something here (display the image using imageView/ convert the image into string) 
} 

질문 : .jpg 형식으로 변환해야하는 이유는 무엇입니까? .gif, .png 등이 될 수 있습니까?

관련 문제