Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 安卓:如何提高我相机的性能_Android_Image_Performance_Size_Android Camera2 - Fatal编程技术网

Android 安卓:如何提高我相机的性能

Android 安卓:如何提高我相机的性能,android,image,performance,size,android-camera2,Android,Image,Performance,Size,Android Camera2,我开发了一个android摄像头应用程序!我使用camera2来实现摄像头模块!问题是当我用它拍照时,图像的大小太大了,大约9MB!!!所以我的画廊太慢了!原因是什么 我在不同的手机上测试,图像的大小不同,但还是太高了!!我尝试了photo.compress(Bitmap.CompressFormat.JPEG,50,out)这段代码可以缩小尺寸,但是图像的质量对我来说太重要了,所以我不想降低分辨率!这是我的相机代码: public class MainActivity extends AppC

我开发了一个android摄像头应用程序!我使用camera2来实现摄像头模块!问题是当我用它拍照时,图像的大小太大了,大约9MB!!!所以我的画廊太慢了!原因是什么

我在不同的手机上测试,图像的大小不同,但还是太高了!!我尝试了
photo.compress(Bitmap.CompressFormat.JPEG,50,out)这段代码可以缩小尺寸,但是图像的质量对我来说太重要了,所以我不想降低分辨率!这是我的相机代码:

public class MainActivity extends AppCompatActivity {

    private Size previewsize;
    private Size jpegSizes[] = null;
    private TextureView textureView;
    private CameraDevice cameraDevice;
    private CaptureRequest.Builder previewBuilder;
    private CameraCaptureSession previewSession;
    private static VirtualFileSystem vfs;
    ImageButton getpicture;
    ImageButton btnShow;
    Button btnSetting;

    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();

    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textureView = (TextureView) findViewById(R.id.textureview);
        textureView.setSurfaceTextureListener(surfaceTextureListener);
        getpicture = (ImageButton) findViewById(R.id.getpicture);
        btnShow = (ImageButton) findViewById(R.id.button2);
        btnSetting = (Button) findViewById(R.id.btn_setting);

        btnSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, Setting.class));
            }
        });

        btnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, Gallery2.class));
            }
        });

        getpicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPicture();
            }
        });

    }

    void getPicture() {
        if (cameraDevice == null) {
            return;
        }
        CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
            if (characteristics != null) {
                jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
            }
            int width = 640, height = 480;
            if (jpegSizes != null && jpegSizes.length > 0) {
                width = jpegSizes[0].getWidth();
                height = jpegSizes[0].getHeight();
            }
            ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
            List<Surface> outputSurfaces = new ArrayList<Surface>(2);
            outputSurfaces.add(reader.getSurface());
            outputSurfaces.add(new Surface(textureView.getSurfaceTexture()));
            final CaptureRequest.Builder capturebuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            capturebuilder.addTarget(reader.getSurface());
            capturebuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            capturebuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
            ImageReader.OnImageAvailableListener imageAvailableListener = new ImageReader.OnImageAvailableListener() {
                @Override
                public void onImageAvailable(ImageReader reader) {
                    Image image = null;
                    try {
                        image = reader.acquireLatestImage();
                        ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                        byte[] bytes = new byte[buffer.capacity()];
                        buffer.get(bytes);                     

                        Bitmap photo = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, null);
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        photo.compress(Bitmap.CompressFormat.JPEG, 50, out);
                        save(out);
                        photo = Bitmap.createScaledBitmap(photo, 120, 120, false);
                        btnShow.setImageBitmap(photo);

                        save(out);
                    } catch (Exception ee) {
                    } finally {
                        if (image != null)
                            image.close();
                    }
                }

                void save(ByteArrayOutputStream bytes) {

                    File file12 = getOutputMediaFile();
                    OutputStream outputStream = null;
                    try {
                        outputStream = new FileOutputStream(file12);
                        outputStream.write(bytes.toByteArray());
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (outputStream != null)
                                outputStream.close();
                        } catch (Exception e) {
                        }
                    }
                }
            };
            HandlerThread handlerThread = new HandlerThread("takepicture");
            handlerThread.start();
            final Handler handler = new Handler(handlerThread.getLooper());
            reader.setOnImageAvailableListener(imageAvailableListener, handler);
            final CameraCaptureSession.CaptureCallback previewSSession = new CameraCaptureSession.CaptureCallback() {
                @Override
                public void onCaptureStarted(CameraCaptureSession session, CaptureRequest request, long timestamp, long frameNumber) {
                    super.onCaptureStarted(session, request, timestamp, frameNumber);
                }

                @Override
                public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                    super.onCaptureCompleted(session, request, result);
                    startCamera();
                }
            };
            cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(CameraCaptureSession session) {
                    try {
                        session.capture(capturebuilder.build(), previewSSession, handler);
                    } catch (Exception e) {
                    }
                }

                @Override
                public void onConfigureFailed(CameraCaptureSession session) {
                }
            }, handler);
        } catch (Exception e) {
        }
    }

    public void openCamera() {
        CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            String camerId = manager.getCameraIdList()[0];
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(camerId);
            StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            previewsize = map.getOutputSizes(SurfaceTexture.class)[0];
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

                return;
            }
            manager.openCamera(camerId, stateCallback, null);
        }catch (Exception e)
        {
        }
    }
    private TextureView.SurfaceTextureListener surfaceTextureListener=new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            openCamera();
        }
        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
        }
        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            return false;
        }
        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {
        }
    };
    private CameraDevice.StateCallback stateCallback=new CameraDevice.StateCallback() {
        @Override
        public void onOpened(CameraDevice camera) {
            cameraDevice=camera;
            startCamera();
        }
        @Override
        public void onDisconnected(CameraDevice camera) {
        }
        @Override
        public void onError(CameraDevice camera, int error) {
        }
    };
    @Override
    protected void onPause() {
        super.onPause();
        if(cameraDevice!=null)
        {
            cameraDevice.close();
        }
    }
    void  startCamera()
    {
        if(cameraDevice==null||!textureView.isAvailable()|| previewsize==null)
        {
            return;
        }
        SurfaceTexture texture=textureView.getSurfaceTexture();
        if(texture==null)
        {
            return;
        }
        texture.setDefaultBufferSize(previewsize.getWidth(),previewsize.getHeight());
        Surface surface=new Surface(texture);
        try
        {
            previewBuilder=cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        }catch (Exception e)
        {
        }
        previewBuilder.addTarget(surface);
        try
        {
            cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(CameraCaptureSession session) {
                    previewSession=session;
                    getChangedPreview();
                }
                @Override
                public void onConfigureFailed(CameraCaptureSession session) {
                }
            },null);
        }catch (Exception e)
        {
        }
    }
    void getChangedPreview()
    {
        if(cameraDevice==null)
        {
            return;
        }
        previewBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
        HandlerThread thread=new HandlerThread("changed Preview");
        thread.start();
        Handler handler=new Handler(thread.getLooper());
        try
        {
            previewSession.setRepeatingRequest(previewBuilder.build(), null, handler);
        }catch (Exception e){}
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    private File getOutputMediaFile() {


        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        File mediaFile;
File(Environment.getExternalStorageDirectory()+"/MyCamAppCipher1"+"/" + mTime + ".jpg");

        mediaFile = new File("/myfiles.db"+"/" + mTime + ".jpg");
        return mediaFile;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}
public类MainActivity扩展了AppCompatActivity{
私有大小预览大小;
私有大小jpegSizes[]=null;
私有纹理视图纹理视图;
私人摄像设备;
私有CaptureRequest.Builder预览Builder;
私人摄像机捕捉会话预览会话;
专用静态虚拟文件系统vfs;
图片按钮;
图像按钮显示;
按钮设置;
专用静态最终SparseIntArray方向=新SparseIntArray();
静止的{
方向。附加(Surface.ROTATION_0,90);
方向。附加(Surface.ROTATION_90,0);
方向。附加(Surface.ROTATION_180,270);
方向。附加(Surface.ROTATION_270,180);
}
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textureView=(textureView)findViewById(R.id.textureView);
setSurfaceTextureListener(SurfaceTextRelister);
getpicture=(ImageButton)findViewById(R.id.getpicture);
btnShow=(图像按钮)findViewById(R.id.button2);
btn设置=(按钮)findViewById(R.id.btn\U设置);
btnSetting.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
startActivity(新意图(MainActivity.this,Setting.class));
}
});
btnShow.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
startActivity(新意图(MainActivity.this,Gallery2.class));
}
});
getpicture.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
getPicture();
}
});
}
void getPicture(){
如果(cameraDevice==null){
返回;
}
CameraManager=(CameraManager)getSystemService(Context.CAMERA_服务);
试一试{
CameraCharacteristics characteristics=manager.getCameraCharacteristics(cameraDevice.getId());
如果(特征!=null){
jpegSizes=characteristics.get(CameraCharacteristics.SCALER\u STREAM\u CONFIGURATION\u MAP).getOutputSizes(ImageFormat.JPEG);
}
内部宽度=640,高度=480;
如果(jpegSizes!=null&&jpegSizes.length>0){
宽度=JPEG大小[0]。getWidth();
高度=JPEG大小[0]。getHeight();
}
ImageReader=ImageReader.newInstance(宽度、高度、ImageFormat.JPEG,1);
List outputSurfaces=新的ArrayList(2);
add(reader.getSurface());
添加(新曲面(textureView.getSurfaceTexture());
final CaptureRequest.Builder capturebuilder=cameraDevice.createCaptureRequest(cameraDevice.TEMPLATE\u STILL\u CAPTURE);
addTarget(reader.getSurface());
capturebuilder.set(CaptureRequest.CONTROL_模式,CameraMetadata.CONTROL_模式自动);
int rotation=getWindowManager().getDefaultDisplay().getRotation();
set(CaptureRequest.JPEG_ORIENTATION,ORIENTATIONS.get(rotation));
ImageReader.OnImageAvailableListener imageAvailableListener=新建ImageReader.OnImageAvailableListener(){
@凌驾
公共图像可用(图像阅读器){
图像=空;
试一试{
image=reader.acquiredlatestimage();
ByteBuffer buffer=image.getPlanes()[0].getBuffer();
字节[]字节=新字节[buffer.capacity()];
buffer.get(字节);
位图照片=BitmapFactory.decodeByteArray(字节,0,字节.长度,null);
ByteArrayOutputStream out=新建ByteArrayOutputStream();
photo.compress(位图.CompressFormat.JPEG,50,输出);
保存(输出);
照片=位图。createScaledBitmap(照片,120,120,假);
btnShow.setImageBitmap(照片);
保存(输出);
}捕获(异常ee){
}最后{
如果(图像!=null)
image.close();
}
}
无效保存(ByteArrayOutputStream字节){
File file12=getOutputMediaFile();
OutputStream OutputStream=null;
试一试{
outputStream=新文件outputStream(文件12);
outputStream.write(bytes.toByteArray());
}捕获(例外e){
e、 printStackTrace();
}最后{
试一试{
if(outputStream!=null)
outputStream.close();
}捕获(例外e){
}
}
}
};
HandlerThread HandlerThread=新HandlerThread(“拍照”);
handlerThread.start();
        int width = 640, height = 480;
        if (jpegSizes != null && jpegSizes.length > 0) {
            width = jpegSizes[0].getWidth();
            height = jpegSizes[0].getHeight();
        }
int width = Integer.MAX_VALUE, height = Integer.MAX_VALUE;
for (int i = 0; i < jpegSizes.length; i++) {
    int currWidth = jpegSizes[0].getWidth();
    int currHeight = jpegSizes[0].getHeight();
    if ((currWidth < width && currHeight < height) &&  // smallest resolution
        (currWidth > 2048  && currHeight > 1536)) {    // at least 3M pixels
        width = currWidth;
        height = currHeight;
    }
}