TextureView获取RGBA

TextureView入门代码

package com.obarong.testtextureview;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.TextureView;

import java.io.IOException;

public class MainActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener {

    private TextureView mTextureView;
    private Camera mCamera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTextureView = new TextureView(this);
        mTextureView.setSurfaceTextureListener(this);
        setContentView(mTextureView);
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        mTextureView.setAlpha(0.5f);
        mTextureView.setRotation(90.0f);

        mCamera = Camera.open();

        try {
            mCamera.setPreviewTexture(surface);
            mCamera.startPreview();
        } catch (IOException ioe) {
            // Something bad happened
        }
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
        mCamera.stopPreview();
        mCamera.release();
        return true;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {

    }
}

获取RGBA

旋转不影响代码获取的宽高。

默认preview格式是yuv420sp

保存成Bitmap用ARGB8888

电脑怎么预览?用YUView。

这是保存成PNG的代码

    public byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

直接保存byte

    public byte[] Bitmap2Bytes(Bitmap bitmap) {
        int bytes = bitmap.getByteCount();
        ByteBuffer buffer = ByteBuffer.allocate(bytes);
        bitmap.copyPixelsToBuffer(buffer); //Move the byte data to the buffer
        return buffer.array();
    }

显示有点问题

把后缀改成argb,显示正常

mTextureView.setRotation旋转和mTextureView.setAlpha设置透明度并不会改变保存的rgba。能改变rgba的是mCamera.setDisplayOrientation

快速拉取手机rgba文件

adb pull storage/sdcard0/texture.argb

源码:
obarong/TestTextureView
https://github.com/obarong/TestTextureView

参考

Android TextureView简易教程 - 泡在网上的日子
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/1213/2153.html

TextureView  |  Android 开发者  |  Android Developers
https://developer.android.com/reference/android/view/TextureView

Android Camera TextureView 获取预览帧_renlei0012的博客-CSDN博客_如何在android studio 使用textureview 的getbitmap函数
https://blog.csdn.net/renlei0012/article/details/90412054

Bitmap与byte[]转换_joey.lei的博客-CSDN博客_bitmap转byte数组
https://blog.csdn.net/lei19880402/article/details/86002482

posted @ 2020-07-31 13:36  奥巴荣  阅读(585)  评论(0编辑  收藏  举报