【问题标题】:Drawable from imageview to byte array (database)可从图像视图绘制到字节数组(数据库)
【发布时间】:2014-04-02 01:01:22
【问题描述】:

我一直在尝试解决我的问题,寻找类似这样的问题 (Drawable to byte[]),但我无法解决。

我正在从 imageview 设置一个可绘制图片(用户也可以更改它),后来我试图获取这张图片并将其转换为字节数组以将其保存在数据库中。

我的代码:

//imageview1.setImageResource(R.drawable.pictureJM);
imageview1.setImageDrawable(getResources().getDrawable(R.drawable.pictureJM));

Drawable d1=imageview1.getDrawable();
Bitmap bitmap =((BitmapDrawable)d1).getBitmap();  <-- (The application stops here)

ByteArrayOutputStream streamJM = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, streamJM);
byte[] imageInByte = streamJM.toByteArray();

你能告诉我有什么问题吗?

【问题讨论】:

  • 我已经尝试过您输入的相同代码,它工作正常。您到底遇到了什么错误?
  • 将资源放入ImageView 而不是直接将资源解码为Bitmap 到底有什么意义? BitmapFactory.decodeResource(context.getResources(), R.drawable.pictureJM)
  • (Arshdeep_somal)- 没有错误,它只是停止执行,但是如果我从图库中放一张带有其他功能的图片,我就可以了……我不明白,很难解释。 (sherpya),我应该如何处理这些代码行?谢谢两位,这个问题我很头疼。

标签: android database imageview bytearray drawable


【解决方案1】:

试试这个:

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pictureJM);
ByteArrayOutputStream streamJM = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, streamJM); 
byte[] imageInByte = streamJM.toByteArray();

【讨论】:

  • 这些代码行有效,但问题是用户可以更改 imageview 的图片,图片不是静态的,所以 "R,drawable.pictureJM" 它只在一种情况下是正确的。
【解决方案2】:

我真的不明白它有什么问题,但最后我修复了。我没有更改代码的任何其他部分,当我编写此代码时它开始工作:

Bitmap bitmap = ((BitmapDrawable)imageview1.getDrawable()).getBitmap();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte=stream.toByteArray();

感谢大家帮助我! 干杯

【讨论】:

    猜你喜欢
    • 2016-09-02
    • 1970-01-01
    • 2013-08-27
    • 2015-08-06
    • 1970-01-01
    • 2013-02-28
    • 2011-12-18
    • 2012-07-28
    • 1970-01-01
    相关资源
    最近更新 更多