繁体   English   中英

Android位图到ByteArray,反之亦然,返回null?

[英]Android bitmap to ByteArray and vice versa returns null?

我试图从java分配直接bytebuffer,从位图填充它并从该缓冲区创建位图。 但结果我得到了null。

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    mCurrentBitmap = BitmapFactory.decodeFile(hardCodedPath, options);

    // 4 - bytes count per pixel
    bytesCount = mCurrentBitmap.getWidth() * mCurrentBitmap.getHeight() * 4;

    pixels = ByteBuffer.allocateDirect((int) bytesCount);
    mCurrentBitmap.copyPixelsToBuffer(this.pixels);

    byte[] bitmapdata = new byte[pixels.remaining()];
    pixels.get(bitmapdata);

    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inPreferredConfig = Bitmap.Config.ARGB_8888;

    Bitmap newBitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, (int) bytesCount, opt);

有人可以帮我理解为什么newBitmap为null?

decodeByteArray()期望编码的位图数据(PNG,JPEG等),而不是简单的RGB(A)字节数组。 要做你想做的事,你可以简单地使用Bitmap.setPixels() 首先,创建一个正确大小/配置的Bitmap( Bitmap.create(width, height, Bitmap.Config.ARGB_8888) )然后在其上调用setPixels(bitmapdata, 0, width, 0, 0, width, height)

由于你有一个ByteBuffer你可以通过调用Bitmap.copyPixelsFromBuffer()更轻松地完成它。 就像使用setPixels() ,首先创建一个正确大小的位图。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM