【问题标题】:Android bitmap to ByteArray and vice versa returns null?Android位图到ByteArray,反之亦然返回null?
【发布时间】:2013-04-19 03:19:55
【问题描述】:

我正在尝试从 java 分配直接字节缓冲区,从位图填充它并从该缓冲区创建位图。但结果我收到空值。

    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 为空?

【问题讨论】:

    标签: java android bitmap buffer


    【解决方案1】:

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

    由于您有ByteBuffer,您可以通过调用Bitmap.copyPixelsFromBuffer() 更轻松地完成此操作。就像setPixels()一样,先创建一个大小合适的位图。

    【讨论】:

      猜你喜欢
      • 2016-12-05
      • 1970-01-01
      • 2018-10-07
      • 2020-02-19
      • 2020-02-15
      • 2014-11-08
      • 2012-02-16
      • 2013-08-16
      • 2012-06-27
      相关资源
      最近更新 更多