在Android Studio中,如何将ImageView转换为字节数组?

10

我的目标是让用户选择一张图片并将其填充到一个图像视图中。然后,在点击按钮时,该图像将被发送到Parse数据库。我知道我必须将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();
 }

“Doesn't seem to work”不是一个很好的问题描述。是否有错误?如果有,是什么错误?代码是否运行但结果出乎意料?如果是这样,你期望看到什么,实际看到了什么? - user94559
谢谢Smarx,一切都正常,除了转换为位图的部分。我认为我没有正确获取图像视图数据。你知道怎么从里面选择图像数据吗? - RealBadCoder
你还没有描述出问题在哪里。你怎么知道“转换为位图”不起作用了? - user94559
因为当我点击sendToParseBtn按钮时,应用程序会崩溃。 - RealBadCoder
当它崩溃时,你得到了什么异常?(日志中显示了什么?) - user94559
2个回答

32

尝试首先将图像视图转换为位图可绘制对象,然后获取字节数组:

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

2
我建议在你的代码末尾添加以下内容:try { baos.close(); } catch (IOException e) { e.printStackTrace(); } - rocknow

0
您可以使用以下方法将imageView转换为bytesArray
public byte[] getBytes(ImageView imageView) {
    try {
        Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] bytesData = stream.toByteArray();
        stream.close();
        return bytesData;
    } catch(Exception e) {
        e.printStackTrace();
        return null;
    }
    return null;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接