java 如何在 Android Studio 中将图像视图转换为字节数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37779515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How Can I convert an imageview to byte array in Android Studio?
提问by RealBadCoder
My goal is to get a picture selected by the user and populate an image view with it. Then, on clicking a button, that image will be sent to a Parse database. I know I have to convert the imageview to byte array, but Doesn't seem to work.
我的目标是获取用户选择的图片并用它填充图像视图。然后,单击一个按钮,该图像将被发送到 Parse 数据库。我知道我必须将 imageview 转换为字节数组,但似乎不起作用。
Any help will be highly appreciated. here's my code:
任何帮助将不胜感激。这是我的代码:
//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();
}
回答by Rogério Peixoto
Try converting the image view to a bitmap drawable first then get the byteArray:
首先尝试将图像视图转换为可绘制的位图,然后获取 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