【问题标题】:Converting bitmap to byteArray android将位图转换为 byteArray android
【发布时间】:2012-04-28 19:55:50
【问题描述】:

我有一个位图,我想通过将其编码为 base64 将其发送到服务器,但我不想以 png 或 jpeg 压缩图像。

现在我之前做的是。

ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY, byteArrayBitmapStream);
byte[] b = byteArrayBitmapStream.toByteArray();
//then simple encoding to base64 and off to server
encodedImage = Base64.encodeToString(b, Base64.NO_WRAP);

现在我不想使用任何压缩,也不想使用任何格式的简单字节 [] 来自我可以编码并发送到服务器的位图。

任何指针?

【问题讨论】:

    标签: android bitmap bytearray base64


    【解决方案1】:

    您可以使用copyPixelsToBuffer() 将像素数据移动到Buffer,也可以使用getPixels() 然后通过位移将整数转换为字节。

    copyPixelsToBuffer() 可能是您想要使用的,因此这里有一个示例说明如何使用它:

    //b is the Bitmap
    
    //calculate how many bytes our image consists of.
    int bytes = b.getByteCount();
    //or we can calculate bytes this way. Use a different value than 4 if you don't use 32bit images.
    //int bytes = b.getWidth()*b.getHeight()*4; 
    
    ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
    b.copyPixelsToBuffer(buffer); //Move the byte data to the buffer
    
    byte[] array = buffer.array(); //Get the underlying array containing the data.
    

    【讨论】:

    • 字节[] b ; ByteBuffer byteBuffer = ByteBuffer.allocate(bitmapPicture.getByteCount()); bitmapPicture.copyPixelsToBuffer(byteBuffer); b = byteBuffer.array(); ???
    • @AsadKhan 我添加了一个示例。
    • @ShailAdi 调用 getByteCount() 您将获得 API 级别 12。
    • 如果您查看 getByteCount() impl,它只是 getRowBytes() * getHeight(),如果您的目标是
    • @iDemigod OP 明确不想使用 Bitmap.Compress()。
    【解决方案2】:

    而不是@jave 答案中的以下行:

    int bytes = b.getByteCount();
    

    使用下面的行和函数:

    int bytes = byteSizeOf(b);
    
    protected int byteSizeOf(Bitmap data) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) {
        return data.getRowBytes() * data.getHeight();
    } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        return data.getByteCount();
    } else {
          return data.getAllocationByteCount();
    }
    

    【讨论】:

      【解决方案3】:
      BitmapCompat.getAllocationByteCount(bitmap);
      

      有助于找到所需的 ByteBuffer 大小

      【讨论】:

        猜你喜欢
        • 2013-04-07
        • 2017-03-24
        • 1970-01-01
        • 2013-07-20
        • 1970-01-01
        • 2010-10-28
        • 2014-04-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多