【问题标题】:Java Android: BufferedInputStream to byte ArrayJava Android:BufferedInputStream 到字节数组
【发布时间】:2014-02-25 18:38:29
【问题描述】:

有谁知道如何将 BufferedInputStream 转换为 byte[] 以便我可以制作它的位图?

那是我的信息流:

BufferedInputStream stream = new BufferedInputStream(socket.getInputStream());

这就是我的字节[]:

byte[] bytes;

【问题讨论】:

    标签: java android stream bytearray bufferedinputstream


    【解决方案1】:

    嗯...BufferedInputStreamread() 方法将为您提供所需的byte[]

    要获取Bitmap,请使用BitmapFactory.decodeStream() 方法并将BufferedInputStream 作为参数传入。好去! :)

    【讨论】:

    • 如此而已; byte[] bytes = BitmapFactory.decodeStream(stream);?
    • Bitmap bitmap = BitmapFactory.decodeStream(stream)
    • +1 最正确的答案。对于透明图片(如:.png),我觉得需要指定BitmapFactory.Options
    • 似乎可以工作,但如果我想将 ImageView 放入我的 LinearLayout 中,它会说:只有创建视图层次结构的原始线程才能触摸它的视图如何解决这个问题?
    • @LittleChild 你应该包括主循环器:new Handel(Looper.getMainLooper()).post(runnable);
    【解决方案2】:

    使用ByteArrayOutputStream:

    BufferedInputStream stream = new BufferedInputStream(s.getInputStream());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
    int theByte;
    
    while((theByte = stream.read()) != -1) baos.write(theByte);
    

    Then:

    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inDither = true;
    opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
    byte[] imageByteArray = bytes;
    Bitmap bitmap = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length, opt);
    imageView.setImageBitmap(bitmap);
    

    【讨论】:

    • BitmapFactory.decodeStream() 因为这样我就可以制作它的位图 :p
    • @LittleChild 更新了答案;)
    • 仍然非常复杂 :D 只需将流传递给 decodeStream() 并让 Android 发挥作用;) 它已超载。 :)
    • @LittleChild 是的,同意!懒得更新两次了:P
    • 我现在试过了,但它说 NullPointerException for outputstream write at: while((theByte = is.read()) != -1) baos.write(bytes);我认为“是”应该意味着流对吗?
    猜你喜欢
    • 2011-10-04
    • 2020-11-18
    • 2018-03-08
    • 2017-04-22
    • 1970-01-01
    • 2015-10-15
    • 2011-11-06
    • 1970-01-01
    相关资源
    最近更新 更多