如何在相机App中将原始byte []转换为位图

时间:2019-02-14 16:40:46

标签: android arrays bitmap camera

这是拍照功能

class Camera {
...

void capturePicture() {
    Camera.Size size = mParams.getPictureSize();
    int bitsPerPixel = ImageFormat.getBitsPerPixel(mParams.getPictureFormat());
    int bufferSize = (int) Math.ceil(size.width * size.height * bitsPerPixel / 8d) ;
    Log.d(TAG, "Picture Size : " + size.width + "\t" + size.height);
    Log.d(TAG, "Picture format : " + mParams.getPictureFormat());
    Log.d(TAG, "Bits per Pixel = " + bitsPerPixel);
    Log.d(TAG, "Buffer Size = " + bufferSize);
    byte[] buffer = new byte[1382400];
    addBuffer(buffer);
    Camera.ShutterCallback shutterCallback = () -> mCameraCallbacks.onShutter();
    Camera.PictureCallback pictureCallback = (data, camera) -> {
        mCameraControllerCallbacks.onPicture(data);
        };
    mCamera.takePicture(shutterCallback, pictureCallback, null, null);
}

public interface CameraCallbacks {
    void onPicture(byte[] bytes);
}

图片大小应该是3264 x 2448,但是bitsPerPixel返回-1,所以我不能用它来计算。结果最小缓冲区大小是1382400,我不知道为什么。

这里是活动接收回调

public class CameraActivity extends AppCompatActivity implements Camera.CameraCallbacks

    @Override
public void onPicture(byte[] bytes) {

    final ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
    final int[] ints = new int[bytes.length / 4];
    buffer.asIntBuffer().put(ints);
    Log.d(TAG,"Creating Bitmap of Size : "+mCameraView.mPictureSize.width +" x "+mCameraView.mPictureSize.height);
    Bitmap bitmap = Bitmap.createBitmap(ints, mCameraView.mPictureSize.width, mCameraView.mPictureSize.height, Bitmap.Config.ARGB_8888);
    Intent intent = new Intent(CameraActivity.this, PicturePreviewActivity.class);
    intent.putExtra("bitmap", bmp);
    startActivityForResult(intent, SAVE_PICTURE_OR_NOT);

}

这里的代码显然是错误的,由于我不知道这些字节内部的数据结构,我无法将这些byte []重新排列为位图接受的ints []形式。 同样,BitmapFactory.decodeByteArray无法工作,因为它无法读取原始数据。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

无法从android相机中检索未压缩的位图数据,因此图片回调需要从RawCallback移至JpegCallback并使用解码字节数组()来获取Bitmap,而且通过Intent传递Bitmap也不可靠,因此这是最简单的方法是直接写到接收方Activity。代码变成这样:

.group()