Android byte array to Bitmap How to

后端 未结 3 1582
面向向阳花
面向向阳花 2020-12-19 07:40

How can I convert byte array received using socket.

  1. The C++ client send image data which is of type uchar.

  2. At the android side I am receivin

3条回答
  •  遥遥无期
    2020-12-19 08:08

    I've been using it like below in one of my projects and so far it's been pretty solid. I'm not sure how picky it is as far as it not being compressed as a PNG though.

    byte[] bytesImage;
    Bitmap bmpOld;   // Contains original Bitmap
    Bitmap bmpNew;
    
    ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
    bmpOld.compress(Bitmap.CompressFormat.PNG, 100, baoStream);
    bytesImage = baoStream.toByteArray();
    bmpNew = BitmapFactory.decodeByteArray(bytesImage, 0, bytesImage.length);
    

    edit: I've adapted the code from this post to use RGB, so the code below should work for you. I haven't had a chance to test it yet so it may need some adjusting.

    Byte[] bytesImage = {0,1,2, 0,1,2, 0,1,2, 0,1,2};
    int intByteCount = bytesImage.length;
    int[] intColors = new int[intByteCount / 3];
    int intWidth = 2;
    int intHeight = 2;
    final int intAlpha = 255;
    if ((intByteCount / 3) != (intWidth * intHeight)) {
        throw new ArrayStoreException();
    }
    for (int intIndex = 0; intIndex < intByteCount - 2; intIndex = intIndex + 3) {
        intColors[intIndex / 3] = (intAlpha << 24) | (bytesImage[intIndex] << 16) | (bytesImage[intIndex + 1] << 8) | bytesImage[intIndex + 2];
    }
    Bitmap bmpImage = Bitmap.createBitmap(intColors, intWidth, intHeight, Bitmap.Config.ARGB_8888);
    

提交回复
热议问题