分享

Android OpenGL YUV 旋转花屏解决、Camera获取图像

 QomoIT 2019-07-04

一个自拍app,如何获取我们的surface view的截屏?

在Camera的onPreviewFrame回调中(继承的PreviewCallback接口)。我们可以获取到data数组,里面存放着就是实时的图片

data数组转文件为null,且转bitmap也为null怎么办?

data数组里确实存放的是图片,但是格式不对,是YUV420格式。需要进行一个转换。所以采用open gl包下的YuvImage这个类可以解决转化的问题,他有一个compressToJpeg方法。

转换成jpg格式,存到手机文件中,发现图片与拍摄出来的不符合,是经过90度旋转的图像怎么办(这里采用的是手机前置摄像头)?

对byte数组进行1.旋转2.镜像翻转(避免获取出来是反的)即可。再给算法处理后的新数组交给YUV去转换即可。

转换出来发现方向是对了,但是花屏了怎么办(这里是屏幕中出现了4个人并且重影了)?

是因为对byte数组旋转后,比如原来是100*200,旋转后就成了200*100,这个时候你不能把100,200分别交给YUV的宽高了,因为你大小都没指定对,解码自然会错误。而是应该给200,100。

代码

图片数组

public void onPreviewFrame(byte[] data, Camera camera) {

就是这个data

顺时针旋转270度代码

private byte[] rotateYUVDegree270AndMirror(byte[] data, int imageWidth, int imageHeight) {byte[] yuv = new byte[imageWidth * imageHeight * 3 / 2];// Rotate and mirror the Y luma    int i = 0;int maxY = 0;for (int x = imageWidth - 1; x >= 0; x--) {
        maxY = imageWidth * (imageHeight - 1) + x * 2;for (int y = 0; y < imageHeight; y++) {
            yuv[i] = data[maxY - (y * imageWidth + x)];
            i++;
        }
    }// Rotate and mirror the U and V color components    int uvSize = imageWidth * imageHeight;
    i = uvSize;int maxUV = 0;for (int x = imageWidth - 1; x > 0; x = x - 2) {
        maxUV = imageWidth * (imageHeight / 2 - 1) + x * 2 + uvSize;for (int y = 0; y < imageHeight / 2; y++) {
            yuv[i] = data[maxUV - 2 - (y * imageWidth + x - 1)];
            i++;
            yuv[i] = data[maxUV - (y * imageWidth + x)];
            i++;
        }
    }return yuv;
}

使用

Camera.Size previewSize = mCamera.getParameters().getPreviewSize();//获取照相机宽高byte[] newData = rotateYUVDegree270AndMirror(data, previewSize.width, previewSize.height);

交换宽高传入YUV

YuvImage yuvimage = new YuvImage(
        newData,
        ImageFormat.NV21,
        previewSize.height,//这里交换了宽高
        previewSize.width,null);

解码,宽高也是反向传入

FileOutputStream f = null;try {
    f = new FileOutputStream(file);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
yuvimage.compressToJpeg(new Rect(0, 0, previewSize.height, previewSize.width), 100, f);try {
    f.flush();
    f.close();
} catch (IOException e) {
    e.printStackTrace();
}

搞定了,经过解码、旋转、镜像翻转、IO的byte数组,成功转化成正常图片文件保存到了本地!

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多