camera.takePicture() is crashing my app

前端 未结 3 1633
甜味超标
甜味超标 2020-12-21 11:31

I have an app that is supposed to take pictures using the camera.takePicture. The code I use is the following :

private Bitmap bitmapPicture;
//inside onCrea         


        
3条回答
  •  感情败类
    2020-12-21 11:42

    Use this simple code to capture using the device camera

    IMP Note: Add those permision to the mainfest file

    
    
    

    The mainActivity

    public class MainActivity extends Activity {
    
    private static final int CAMERA_PIC_REQUEST = 1111;//Constant ID for ActivityResult
    private ImageView mImage; // To display the thumbnail
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        mImage = (ImageView) findViewById(R.id.camera_image);
    
        // Start an intent for Camera Capture with ResultActivity
        Intent cameraIntent = new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
    
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_PIC_REQUEST) {
            // Get the image in a Bitmap extension to assign it to the ImageView
            if (data.getExtras() == null)
                return;
            Bitmap thumb = (Bitmap) data.getExtras().get("data");
            mImage.setImageBitmap(thumb);
    
            // Compress the Bitmap image into JPEG to save it on the device
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumb.compress(Bitmap.CompressFormat.JPEG, 100, bytes);// 100 is the scale..for less quality decrease the number                                
    
            // Save the image on the root SDCard
            File file = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "imageName.png");
    
            try {
                // Create the file to save the image
                file.createNewFile();
                FileOutputStream fo = new FileOutputStream(file);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (Exception e) {
            }
    
        }
    
    }
    
    }
    

    Put This in your Layout MainActivity.XML :

        
    

提交回复
热议问题