【问题标题】:How Can I convert an imageview to byte array in Android Studio?如何在 Android Studio 中将 imageview 转换为字节数组?
【发布时间】:2016-06-12 22:07:26
【问题描述】:

我的目标是获取用户选择的图片并用它填充图像视图。然后,单击按钮时,该图像将被发送到 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();
 }

【问题讨论】:

  • “似乎不起作用”并不是对问题的一个很好的描述。有错误吗?如果是这样,是什么?代码是否运行但有意外结果?如果是这样,你期待什么?你看到了什么?
  • thx smarx,除了转换为位图外,一切正常。我认为我没有正确获取图像视图数据。你知道如何从中选择图像数据吗?
  • 您还没有描述问题所在。你怎么知道“位图转换”不起作用?
  • 因为当我点击 sendToParseBtn 按钮时应用程序崩溃
  • 当它崩溃时,你得到什么异常? (日志中显示了什么?)

标签: java android


【解决方案1】:

尝试先将图像视图转换为可绘制的位图,然后获取 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

【讨论】:

  • 我建议在代码末尾添加try { baos.close(); } catch (IOException e) { e.printStackTrace(); }
【解决方案2】:

您可以使用以下方法将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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2012-01-28
    • 2016-11-02
    • 1970-01-01
    相关资源
    最近更新 更多