2014-01-17 3 views
12

Эй, я не уверен, почему это происходит каждый раз, когда я выбираю изображение в своей галерее?BitmapFactory Невозможно декодировать поток

Вот код:

if (v == uploadImageButton) { 
         // below allows you to open the phones gallery 
         Intent intent = new Intent(); 
         intent.setType("image/*"); 
         intent.setAction(Intent.ACTION_GET_CONTENT); 
         startActivityForResult(
             Intent.createChooser(intent, "Complete action using"), 1); 
       } 


public void onActivityResult(int requestCode, int resultCode, Intent data) { 
       if (resultCode == RESULT_OK && requestCode == 1 && null != data) { 
         // Bitmap photo = (Bitmap) data.getData().getPath(); 
         Uri selectedImageUri = data.getData(); 
         String[] filePathColumn = { MediaStore.Images.Media.DATA }; 

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

         int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
         String picturePath = cursor.getString(columnIndex); 
         cursor.close(); 
         Log.e("Picture", picturePath); 
         decodeFile(picturePath); 
       } 
     } 


public void decodeFile(String filePath) { 
       // TODO Auto-generated method stub 
       // Decode image size 
       BitmapFactory.Options o = new BitmapFactory.Options(); 
       o.inJustDecodeBounds = true; 
       BitmapFactory.decodeFile(filePath, o); 

       // the new size we want to scale to 
       final int REQUIRED_SIZE = 1024; 

       // Find the correct scale value. It should be the power of 2. 
       int width_tmp = o.outWidth, height_tmp = o.outHeight; 
       int scale = 1; 
       while (true) { 
         if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) { 
           break; 
         } 
         width_tmp /= 2; 
         height_tmp /= 2; 
         scale *= 2; 
       } 

       // decode with inSampleSize 
       BitmapFactory.Options o2 = new BitmapFactory.Options(); 
       o2.inSampleSize = scale; 
       Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2); 

       imageview.setImageBitmap(bitmap); 
     } 

Ошибка:

01-17 23:18:04.642: D/Documents(25157): onFinished() [content://com.android.providers.media.documents/document/image%3A901] 
01-17 23:18:04.682: E/BitmapFactory(24993): Unable to decode stream: java.lang.NullPointerException 
01-17 23:18:04.682: E/BitmapFactory(24993): Unable to decode stream: java.lang.NullPointerException 
01-17 23:18:09.732: I/InputReader(766): Reconfiguring input devices. changes=0x00000004 
01-17 23:18:09.732: I/InputReader(766): Device reconfigured: id=4, name='touch_dev', size 1080x1920, orientation 3, mode 1, display id 0 
+0

В чем вопрос? – codeMagic

+0

Любое изображение, которое я выбираю, не разрушает приложение, но я просто получаю эту ошибку ... BitmapFactory Невозможно декодировать поток: java.lang.NullPointerException – Lion789

+0

Опубликовать полный журнал ошибок. Что-то похоже на «null» – codeMagic

ответ

21

Не думайте, что есть путь к файлу. Android 4.4 и выше собираются их удалить. И ури у тебя уже нет пути.

Вы по-прежнему можете получить доступ к содержимому файла либо через InputStream (ContentResolver#openInputStream(Uri uri)), либо через файловый дескриптор.

Это объясняется здесь: ContentProviders: Open a document (прокрутите вниз, ссылку на раздел, кажется, сломана)

И это действительно работает на старых андроид версии тоже.

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (resultCode == RESULT_OK && requestCode == 1 && null != data) { 
     decodeUri(data.getData()); 
    } 
} 

public void decodeUri(Uri uri) { 
    ParcelFileDescriptor parcelFD = null; 
    try { 
     parcelFD = getContentResolver().openFileDescriptor(uri, "r"); 
     FileDescriptor imageSource = parcelFD.getFileDescriptor(); 

     // Decode image size 
     BitmapFactory.Options o = new BitmapFactory.Options(); 
     o.inJustDecodeBounds = true; 
     BitmapFactory.decodeFileDescriptor(imageSource, null, o); 

     // the new size we want to scale to 
     final int REQUIRED_SIZE = 1024; 

     // Find the correct scale value. It should be the power of 2. 
     int width_tmp = o.outWidth, height_tmp = o.outHeight; 
     int scale = 1; 
     while (true) { 
      if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) { 
       break; 
      } 
      width_tmp /= 2; 
      height_tmp /= 2; 
      scale *= 2; 
     } 

     // decode with inSampleSize 
     BitmapFactory.Options o2 = new BitmapFactory.Options(); 
     o2.inSampleSize = scale; 
     Bitmap bitmap = BitmapFactory.decodeFileDescriptor(imageSource, null, o2); 

     imageview.setImageBitmap(bitmap); 

    } catch (FileNotFoundException e) { 
     // handle errors 
    } catch (IOException e) { 
     // handle errors 
    } finally { 
     if (parcelFD != null) 
      try { 
       parcelFD.close(); 
      } catch (IOException e) { 
       // ignored 
      } 
    } 
} 
+0

Хорошо, когда вы это реализуете, мне говорят, что я хочу попробовать попробовать поймать вход? а затем инициализировать вход = null? я делаю что-то неправильно или? – Lion789

+1

@ Lion789 oops, да извините. Обновленный код. – zapl

+0

спасибо, что, похоже, сделал трюк – Lion789

Смежные вопросы