簡體   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