简体   繁体   中英

Determine dark/light by camera on Android

Can someone provide some simple code to determine dark or light with a camera using Android. It doesn't have to be accurate. Only dark or light.

In another posting the lightsensor that is sometimes present in an Android device was suggested which would be ideal, but the 2 android devices I have tested didn't have that sensor. So I go for the camera solution.

I have this code already:

PictureCallback fCallback = new PictureCallback() {

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


camera.stopPreview();
camera.release();

}

camera = Camera.open(0);
Camera.Parameters param=camera.getParameters();
param.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
param.setPictureFormat(ImageFormat.NV21);
camera.setParameters(param);    
camera.startPreview();
camera.takePicture(null, null, fCallback); 

I get valid data using the jpg param imgformat setting, but it would be better if the callback function produces raw rgb data (ie 3x8bit) and then it would be easy to read the value of each byte.

Help is very much appreciated.

I have figured it out myself:

PictureCallback fCallback = new PictureCallback() {
      public void onPictureTaken(byte[] data, Camera camera) {

         Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
          if ((bm.getWidth() > 200) && (bm.getHeight() > 200))
         { 
           int lum = Color.red(bm.getPixel(50, 50));
           lum += Color.red(bm.getPixel(100, 100));
           lum += Color.red(bm.getPixel(150, 150));
           lum += Color.red(bm.getPixel(200, 200));
           lum += Color.green(bm.getPixel(50, 50));
           lum += Color.green(bm.getPixel(100, 100));
           lum += Color.green(bm.getPixel(150, 150));
           lum += Color.green(bm.getPixel(200, 200));
           lum += Color.blue(bm.getPixel(50, 50));
           lum += Color.blue(bm.getPixel(100, 100));
           lum += Color.blue(bm.getPixel(150, 150));
           lum += Color.blue(bm.getPixel(200, 200));
           lum = lum/12;

         if (lum<3)
             tvMain.setText("dark");
        else
             tvMain.setText("light");    

         camready = true;
         }

      }
    };



camera = Camera.open(findFrontFacingCamera());
Camera.Parameters param=camera.getParameters();
param.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
param.set("rawsave-mode", "1");
param.setPictureFormat(ImageFormat.RGB_565);
camera.setParameters(param);  
camera.startPreview();
camera.takePicture(null, null, fCallback);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM