I have this code, but it gives me this:
Unknown URI: content://media/external/images/media
NOTE: I DO have permissions for Camera / Write.
This is my code:
public class MainActivity extends Activity {
// ...
Camera.PictureCallback photoCallback=new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(getApplicationContext(),
"Image saved: " + uriTarget.toString(),
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finish();
}
};
// ...
}
Any suggestions?
// Here is the example for surface view.
public void takePictureNoPreview(Context context) { // open back facing camera by default
Camera myCamera=Camera.open();
if(myCamera!=null) {
try { // set camera parameters if you want to
// here, the unused surface view and holder
SurfaceView dummy=new SurfaceView(context);
myCamera.setPreviewDisplay(dummy.getHolder());
myCamera.startPreview();
myCamera.takePicture(null, null, getJpegCallback());
} finally {
myCamera.close();
}
} else {
// booo, failed!
}
}
private PictureCallback getJpegCallback() {
PictureCallback jpeg = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream fos;
try {
fos = new FileOutputStream("test.jpeg");
fos.write(data); fos.close();
} catch (IOException e) {
//do something about it
}
}
};
return jpeg;
}
// Selecting front facing camera.
private Camera openFrontFacingCameraGingerbread() {
int cameraCount = 0; Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for ( int camIdx = 0; camIdx < cameraCount; camIdx++ ) {
Camera.getCameraInfo( camIdx, cameraInfo );
if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ) {
try {
cam = Camera.open( camIdx );
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam;
}
// This should work...
Related
Is there any way to get photo without preview and put it to database in android sdk 19
In the below code automaticly getting location on every 5 minutes and putting marker on map additionally i need to take photo automaticly and put it to database
public void startCountDown() {
if (this._countDownTimer != null) {
this._countDownTimer.cancel();
}
_countDownTimer = new CountDownTimer(60000 * 5, 60000*5) {
#Override
public void onFinish() {
}
#Override
public void onTick(long millisUntilFinished) {
putMarkerToLocation();
takePhotoAndSaveIt2Db(); // ==> here what i need
}
}.start();
}
Below service works percfectly on api19
public class CapPhoto extends Service {
private Camera mCamera;
#Override
public void onCreate() {
super.onCreate();
Log.d("CAM", "start");
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Thread myThread = null;
}
#Override
public void onStart(Intent intent, int startId) {
takePhoto();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void takePhoto() {
System.out.println("Fotoraf Cekimi Hazirligi Basladi");
Camera camera = null;
int cameraCount = 0;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
SystemClock.sleep(1000);
Camera.getCameraInfo(camIdx, cameraInfo);
try {
camera = Camera.open(camIdx);
} catch (RuntimeException e) {
System.out.println("Camera not available: " + camIdx);
camera = null;
//e.printStackTrace();
}
try {
if (null == camera) {
System.out.println("Could not get camera instance");
} else {
System.out.println("Got the camera, creating the dummy surface texture");
//SurfaceTexture dummySurfaceTextureF = new SurfaceTexture(0);
try {
//camera.setPreviewTexture(dummySurfaceTextureF);
camera.setPreviewTexture(new SurfaceTexture(0));
camera.startPreview();
} catch (Exception e) {
System.out.println("Could not set the surface preview texture");
e.printStackTrace();
}
camIdx = cameraCount;
Camera.Parameters params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
params.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO);
params.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
params.setExposureCompensation(0);
params.setPictureFormat(ImageFormat.JPEG);
params.setJpegQuality(100);
params.setRotation(90);
camera.setParameters(params);
camera.takePicture(null, null, new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFileDir =new File(Environment.getExternalStorageDirectory(), "A");
if(!pictureFileDir.exists()){
pictureFileDir.mkdirs();
} // File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "TaksiResim_" + "_" + date + ".jpg";
String filename = pictureFileDir.getPath() + File.separator + photoFile;
File mainPicture = new File(filename);
//addImageFile(mainPicture);
try {
FileOutputStream fos = new FileOutputStream(mainPicture);
fos.write(data);
fos.close();
System.out.println("resim kayit edildi");
} catch (Exception error) {
System.out.println("resim kayit edilemedi");
}
camera.release();
}
});
}
} catch (Exception e) {
camera.release();
}
}
} }
I am trying to make selfie application. I captured image and saved it from front camera. But in gallery or from file manager image is not being open.
"cannot load image" this message is coming. If i change flag from front camera to back camera it is perfectly working.
public class Preview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
private Context context;
private String TAG = "Preview";
public Preview(Camera mCamera, Context context) {
super(context);
this.mCamera = mCamera;
this.context = context;
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
#Override
public void surfaceCreated(SurfaceHolder mHolder) {
safeCameraOpen();
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
mCamera.release();
mCamera = null;
}
} else {
Log.d(TAG, "Error in camera : ");
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (mCamera != null) {
setCameraDisplayOrientation((Activity) context, mCamera);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
releaseCameraAndPreview();
}
// This method is called while clicking for selfie
public void captureImage() {
mCamera.takePicture(null, null, mPicture);
}
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
saveImage(data);
}
};
public void saveImage(byte[] data) {
try {
File imageFile = createImageFile();
if (imageFile != null) {
FileOutputStream fos = new FileOutputStream(imageFile);
fos.write(data);
fos.close();
Toast.makeText(context, "New Image saved", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Directory problem", Toast.LENGTH_LONG).show();
}
} catch (Exception error) {
error.getMessage();
Toast.makeText(context, "Image could not be saved.", Toast.LENGTH_LONG).show();
}
}
private File createImageFile() throws IOException {
// Create an image file name
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Selfie");
if (!storageDir.exists() && !storageDir.mkdirs()) {
Log.d(TAG, "Can't create directory to save image.");
Toast.makeText(context, "Can't create directory to save image.", Toast.LENGTH_LONG).show();
return null;
}
File image = File.createTempFile(String.valueOf(System.currentTimeMillis()), /* prefix */ ".jpg", /* suffix */ storageDir /* directory */);
return image;
}
private boolean safeCameraOpen() {
boolean qOpened = false;
try {
releaseCameraAndPreview();
mCamera = openFrontFacing();
qOpened = (mCamera != null);
} catch (Exception e) {
e.printStackTrace();
}
return qOpened;
}
public void releaseCameraAndPreview() {
// mPreview.setCamera(null);
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
private Camera openFrontFacing() {
int cameraCount = 0;
Camera camera = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
camera = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return camera;
}
}
in openFrontFacing() method if i change CAMERA_FACING_FRONT to CAMERA_FACING_BACK it is working perfectly.
every camera has some supported preview sizes and picture sizes, you have to set the correct ones. Its a bit longer topic, search for mCamera.getParameters().getSupportedPictureSizes(); and mCamera.getParameters().getSupportedPreviewSizes();
The following code is in service that takes picture in background. It is working fine for all the version below lollipop but gives run-time exception in takePicture(null,null,mcall). Any ideas..?
public void takePictures(final int delay)
{
final Camera.PictureCallback mCall = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.e(TAG, "Picture taken, saving....");
Uri uriTarget = getContentResolver().insert//(Media.EXTERNAL_CONTENT_URI, image);
(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Log.e("Image saved: ", uriTarget.toString());
savePictures(getRealPathFromURI(uriTarget.toString()));
mCamera.stopPreview();
mCamera.release();
mCamera = null;
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e("Image not saved: ", e.toString());
} catch (IOException e) {
Log.e("Image not saved:2 ", e.toString());
e.printStackTrace();
}
}
};
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
thread = new Thread(new Runnable() {
#Override
public void run() {
for (int numOfPicturesAlreadyTaken = 0; numOfPicturesAlreadyTaken < numOfPictures; numOfPicturesAlreadyTaken++) {
Log.e(TAG, "Opening camera");
mCamera = Camera.open();
//mCamera.setPreviewDisplay(sv.getHolder());
parameters = mCamera.getParameters();
parameters.setRotation(90);
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
Thread.sleep(delay);
}
}
});
thread.start();
} else {
Toast.makeText(this, "No camera found.", Toast.LENGTH_SHORT).show();
}
}
the error
come in lollipop only
the code is in service that take picture in background .
java.lang.RuntimeException: takePicture failed
at android.hardware.Camera.native_takePicture(Native Method)
at android.hardware.Camera.takePicture(Camera.java:1436)
at android.hardware.Camera.takePicture(Camera.java:1381)
at com.codebrew.lockdown.services.CameraService$2.run(CameraService.java:133)
at java.lang.Thread.run(Thread.java:818)
I'm trying to take a picture in Android using the code below. The current code doesn't work, namely i cant find the picture inside my phone's storage.
public class CameraShooting implements SurfaceHolder.Callback {
Context context;
Camera camera;
CameraInfo camerainfo;
Camera.Parameters paras;
SurfaceView surfaceview;
SurfaceHolder surfaceholder;
PictureCallback picturecallback;
SurfaceHolder.Callback callback = (SurfaceHolder.Callback) this;
public CameraShooting(Context context) {
this.context = context;
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
surfaceview = new SurfaceView(context);
surfaceholder = surfaceview.getHolder();
surfaceholder.addCallback(callback);
}
};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
int numbersofCamera = camera.getNumberOfCameras();
camerainfo = new CameraInfo();
/*
* for(int i =0; i < numbersofCamera; i++){ Camera.getCameraInfo(i,
* camerainfo); if (camerainfo.facing ==
* CameraInfo.CAMERA_FACING_FRONT){ camera.open(i); }}
*/
camera.open(0);
try {
camera.setPreviewDisplay(surfaceholder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
camera.takePicture(null, null, mPicture);
Toast.makeText(context, "Picture taken", Toast.LENGTH_SHORT).show();
};
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS
), "picture taken");
try {
OutputStream fos = new BufferedOutputStream(new FileOutputStream(pictureFile));
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
};
};
}
Note, I already included
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Try:
fos.flush();
before you close the OutputStream.
I have developed an android application. In that i have used front facing camera functionality. Its working fine but I need to auto capture. i.e. without click shutter button sound, I want to capture photocode..
my camera activity code is
private Camera openFrontFacingCameraGingerbread() {
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for ( int camIdx = 0; camIdx < cameraCount; camIdx++ ) {
Camera.getCameraInfo( camIdx, cameraInfo );
if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ) {
try {
cam = Camera.open( camIdx );
} catch (RuntimeException e) {
Log.i("Camera failed to open: ",e.getLocalizedMessage());
}
}
}
return cam;
}
Thanks in advance..
Follow the steps outlined in the Android Developer reference pages. There's no requirement to have a 'shutter button'. You can create a dummy SurfaceHolder if you don't want to show the image on the screen, e.g.
SurfaceView surface = new SurfaceView(context);
cam.setPreviewDisplay(surface.getHolder());
public int intPicTaken;
// setPreviewCallback on the camera, wait intil intPicTaken increments to 10, then take the picture
cam.setPreviewCallback(prevCallBack);
public Camera.PreviewCallback prevCallBack = new Camera.PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
intPicTaken++;
try {
if(intPicTaken == 10) {
doTakePicture();
}
} catch (Exception e) {
System.out.println("onPreviewFrame: " + e.toString());
}
}
};
public Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
System.out.println("PictureCallback onPictureTaken");
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap picture = BitmapFactory.decodeByteArray(data, 0, data.length, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
picture.compress(Bitmap.CompressFormat.JPEG, 100, baos);
baos.close();
System.out.println("PictureCallback onPictureTaken done");
cam.release();
saveFile(picture);
} catch (Exception e) {
System.out.println("onPictureTaken: " + e.toString());
}
}
};
// take the picture
public void doTakePicture() {
try {
cam.stopPreview();
cam.takePicture(null, null, mPicture, mPicture);
} catch(Exception e){
System.out.println("doTakePicture: " + e.toString());
}
}
// saving the file to gallery
public void saveFile(Bitmap bitmap) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaStorageDir = Environment.getExternalStorageDirectory();
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
System.out.println("saveFile: failed to create directory");
return;
}
}
try {
String saved = MediaStore.Images.Media.insertImage(this.getContentResolver(), bitmap, "title", "description");
Uri sdCardUri = Uri.parse("file://" + Environment.getExternalStorageDirectory());
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, sdCardUri));
System.out.println("file saved");
} catch (Exception e) {
System.out.println("saveFile: " + e.toString());
e.printStackTrace();
}
}
write this code in on create to auto capture image
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom__camera_activity);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
{
mCamera.takePicture(null, null, mPicture);
}
}
}, 5500);
}