2016-06-12 77 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

相关问题