2012-04-24 2 views
24

У меня есть два вида деятельности. Один для вытягивания изображения с SD-карты и один для подключения Bluetooth.Изображение Uri to bytesarray

Я использовал Bundle для передачи Uri изображения от деятельности 1.

Теперь то, что я хочу сделать, это получить, что Ури в деятельности Bluetooth, чтобы и превратить его в передаваемое состояние через массивы байт я видели некоторые примеры, но я не могу заставить их работать для моего кода!

Bundle goTobluetooth = getIntent().getExtras(); 
    test = goTobluetooth.getString("ImageUri"); 

Это то, что я должен перетащить, Что будет следующим шагом?

Большое спасибо

Джейк

ответ

58

От Uri получить byte[] я делаю следующие вещи,

InputStream iStream = getContentResolver().openInputStream(uri); 
byte[] inputData = getBytes(iStream); 

и метод getBytes(InputStream) является:

public byte[] getBytes(InputStream inputStream) throws IOException { 
     ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); 
     int bufferSize = 1024; 
     byte[] buffer = new byte[bufferSize]; 

     int len = 0; 
     while ((len = inputStream.read(buffer)) != -1) { 
     byteBuffer.write(buffer, 0, len); 
     } 
     return byteBuffer.toByteArray(); 
    } 
+0

getContentResolver() openInputStream (тест); получает ошибку, говоря, что она неприменима для аргументов для строки !! В отношении моего кода над его состояниями uri находится в строчной форме, как я могу изменить это, чтобы он совпал с кодом, который вы указали выше! – user1314243

+0

test - это строковая переменная, которую вы должны пройти Uri. Сделайте Ури из теста, а затем передайте его методу. – user370305

+0

Uri uri = Uri.parse (тест); Попробуйте это. – user370305

0

использование getContentResolver() .openInputStream (URI), чтобы получить InputStream из URI. а затем прочитать данные из InputStream преобразования данных в байт [] из этого InputStream

Try с помощью следующего кода

public byte[] readBytes(Uri uri) throws IOException { 
      // this dynamically extends to take the bytes you read 
     InputStream inputStream = getContentResolver().openInputStream(uri); 
      ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); 

      // this is storage overwritten on each iteration with bytes 
      int bufferSize = 1024; 
      byte[] buffer = new byte[bufferSize]; 

      // we need to know how may bytes were read to write them to the byteBuffer 
      int len = 0; 
      while ((len = inputStream.read(buffer)) != -1) { 
      byteBuffer.write(buffer, 0, len); 
      } 

      // and then we can return your byte array. 
      return byteBuffer.toByteArray(); 
     } 

см это ссылки

+8

Что разница между ответом и у меня? – user370305

+0

Название метода: –

0

Этот код работает для меня

Uri selectedImage = imageUri; 
      getContentResolver().notifyChange(selectedImage, null); 
      ImageView imageView = (ImageView) findViewById(R.id.imageView1); 
      ContentResolver cr = getContentResolver(); 
      Bitmap bitmap; 
      try { 
       bitmap = android.provider.MediaStore.Images.Media 
       .getBitmap(cr, selectedImage); 

       imageView.setImageBitmap(bitmap); 
       Toast.makeText(this, selectedImage.toString(), 
         Toast.LENGTH_LONG).show(); 
       finish(); 
      } catch (Exception e) { 
       Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT) 
         .show(); 

       e.printStackTrace(); 
      } 
0

Лучшая практика Java: никогда не забудьте закрыть каждый поток, который вы открываете! Это моя реализация:.

/** 
* get bytes array from Uri. 
* 
* @param context current context. 
* @param uri uri fo the file to read. 
* @return a bytes array. 
* @throws IOException 
*/ 
public static byte[] getBytes(Context context, Uri uri) throws IOException { 
    InputStream iStream = context.getContentResolver().openInputStream(uri); 
    try { 
     return getBytes(iStream); 
    } finally { 
     // close the stream 
     try { 
      iStream.close(); 
     } catch (IOException ignored) { /* do nothing */ } 
    } 
} 



/** 
* get bytes from input stream. 
* 
* @param inputStream inputStream. 
* @return byte array read from the inputStream. 
* @throws IOException 
*/ 
public static byte[] getBytes(InputStream inputStream) throws IOException { 

    byte[] bytesResult = null; 
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); 
    int bufferSize = 1024; 
    byte[] buffer = new byte[bufferSize]; 
    try { 
     int len; 
     while ((len = inputStream.read(buffer)) != -1) { 
      byteBuffer.write(buffer, 0, len); 
     } 
     bytesResult = byteBuffer.toByteArray(); 
    } finally { 
     // close the stream 
     try{ byteBuffer.close(); } catch (IOException ignored){ /* do nothing */ } 
    } 
    return bytesResult; 
} 
0
public void uriToByteArray(String uri) 
    { 

     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     FileInputStream fis = null; 
     try { 
      fis = new FileInputStream(new File(uri)); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 

     byte[] buf = new byte[1024]; 
     int n; 
     try { 
      while (-1 != (n = fis.read(buf))) 
       baos.write(buf, 0, n); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     byte[] bytes = baos.toByteArray(); 
    } 
Смежные вопросы