2016-06-12 57 views
1

我的目標是獲取用戶選擇的圖片並使用它填充圖像視圖。然後,在點擊一個按鈕時,該圖像將被髮送到Parse數據庫。我知道我必須將imageview轉換爲字節數組,但似乎不工作。如何在Android Studio中將imageview轉換爲字節數組?

任何幫助將不勝感激。 這裏是我的代碼:

//send the imageviwew to parse database 

public void sendToParseBtn (View view){ 
    Bitmap bitmapImage = findViewById (R.id.imageView); 
    ImageView imageView = (ImageView) findViewById(R.id.imageView); 
    imageView.setImageBitmap(bitmapImage); 

    ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
    bitmapImage.compress(Bitmap.CompressFormat.JPEG, 40, stream); 

    byte[] byteArray = stream.toByteArray(); 

    ParseFile file = new ParseFile("an.jpg",byteArray); 
    ParseObject object = new ParseObject("MyParseObject"); 
    object.put("imageFile", file); 

    object.saveInBackground(); 
} 
+0

「似乎不工作」是沒有問題的一個偉大的說明。有錯誤嗎?如果是這樣,什麼?代碼是否運行但有意想不到的結果?如果是這樣,你期望什麼,你看到了什麼? – smarx

+0

thx smarx,一切工作除了轉換爲位圖。我認爲我沒有得到正確的圖像視圖數據。你知道我該如何從中選擇圖像數據? – RealBadCoder

+0

你還沒有描述什麼是錯的。你怎麼知道*「轉換爲位圖」不起作用? – smarx

回答

13

嘗試圖像視圖轉換爲位圖繪製第一,然後得到的ByteArray:

ImageView imageView = (ImageView) findViewById(R.id.imageView); 
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap(); 
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
byte[] imageInByte = baos.toByteArray(); 
//save your stuff 
+1

你,SIR,是最好的!這工作完美!我怎麼能給你付錢? – RealBadCoder

+1

我建議添加 '試一下baos.close(); catch(IOException e){ e.printStackTrace(); }'到您的代碼的末尾 – rocknow

相關問題