how to capture picture portrait mode set portrait mode? - android

i have camera activity. and i capture picture but in camera preview not show picture portrait mode . how to possible in android . my code below .
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
protected static final int MEDIA_TYPE_IMAGE = 0;
static String FilePAth = "";
Button takePicture;
static String base64string="";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_preview);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(CameraActivity.this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
takePicture = (Button) findViewById(R.id.btnTakePicture);
takePicture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mCamera.takePicture(null, null, mPicture);
}
});
}
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
FilePAth = mediaStorageDir.getPath() + File.separator + "IMG_"
+ timeStamp + ".jpg";
Log.v("log", " FilePAth " + FilePAth);
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Intent returnIntent = new Intent();
returnIntent.putExtra("data", data);
setResult(RESULT_OK, returnIntent);
finish();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
public void onBackPressed() {
Intent returnIntent = new Intent();
returnIntent.putExtra("path", FilePAth);
setResult(RESULT_OK, returnIntent);
finish();
};
}
and get data :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("log", " data --> " + data.getByteArrayExtra("data"));
if (requestCode == 1) {
if (data.hasExtra("data")) {
Log.v("log", " request if ");
Bitmap b = BitmapFactory.decodeByteArray(
data.getByteArrayExtra("data"), 0,
data.getByteArrayExtra("data").length);
imgStorePicture.setImageBitmap(b);
/*imgStorePicture.setScaleType(ScaleType.FIT_XY);*/
base64string = Base64.encodeBytes(data
.getByteArrayExtra("data"));
Log.v("log", "base64string " + base64string);
}
}
}

The short answer is, you cannot. The picture is always returned the way it is. You can change preview orientation, but not the orientation of the JPEG image returned to your onPictureTaken).
But you can set JPEG rotation via Exif header without decoding it. This is the most efficient method, but some viewers may still show a rotated image.
Alternatively, you can use JPEG lossless rotation. The Android port is on GitHub.

Related

How to store image captured using camera.takePicture(null,null,mPicture) so that it can be displayed it in next activity?

I am making a custom camera application in android. I capture the image using
camera.takePicture(null,null,mPicture)" and "Camera.PictureCallBack()
I want to store the image taken from the camera so that I can display it in the next activity. How can it be done?
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
Pass uri in extras of your next activity intent
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE_USING_CAMERA) {
try {
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putExtra("uri",outputFileUri);
startActivity(i);
} catch (Exception ex) {
Log.e("Exception", ex.toString());
}
}
}
}
then retrieve image in your second activity
Uri = getIntent().getExtras("uri");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
final Bitmap capturedimage = BitmapFactory.decodeFile(uri, options);
imgPreview.setImageBitmap(capturedimage );
TO open Camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, SELECT_PICTURE_USING_CAMERA);
Then need to implement onActivityResult to get the data.
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE_USING_CAMERA) {
try {
final File file = new File(outputFileUri.getPath());
} catch (Exception ex) {
Log.e("Exception", ex.toString());
}
}
}
}
Then you can take the image form the file path to display in the next activity.
You can use CameraView to implement the custom camera in very simple way which gives you the functionalities to capture image and video. You can see the DEMO where it the CameraActivity tooks the picture and PicturePreviewActivity and VideoPreviewActivity are use to preview the picture and video taken in CameraActivity.

Crash app For Android kitkat in Camera app in android

i Develop custom camera app in android but when i store image in external storage .and android 2.3 to 4.2.0 is complete work but android kitkat version not working .what's problem . my custom camera activity code below.
Please Help me!!
public class CameraActivity extends Activity {
Camera mCamera;
CameraPreview mCameraPreview;
protected static final int MEDIA_TYPE_IMAGE = 0;
static String FilePAth = "";
Button takePicture, btnGlr, btnCancelCamera;
static String base64string = "";
String ImageType;
Boolean isSDPresent;
final int RESULT_LOAD_IMAGE = 1;
File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_preview);
isSDPresent = android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(CameraActivity.this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
takePicture = (Button) findViewById(R.id.btnTakePicture);
takePicture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mCamera.takePicture(null, null, mPicture);
}
});
Intent intent = getIntent();
if (intent.hasExtra("ImageType")) {
ImageType = getIntent().getStringExtra("ImageType").toString();
Log.v("log", " ImageType in Camera Activity -- > " + ImageType);
}
btnGlr = (Button) findViewById(R.id.btnGallary);
btnGlr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
btnCancelCamera = (Button) findViewById(R.id.btnCancelCamera);
btnCancelCamera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplication(),
MarketPlaceActivity.class);
startActivity(intent);
}
});
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
releaseCamera();
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
private Camera getCameraInstance() {
try {
Log.v("log_tag", "camera try:::" + mCamera);
mCamera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
Log.v("log_tag", "camera catch:::" + mCamera);
releaseCamera();
}
return mCamera;
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
FilePAth = mediaStorageDir.getPath() + File.separator + "IMG_"
+ timeStamp + ".jpg";
Log.v("log", " FilePAth " + FilePAth);
File mediaFile;
mediaFile = new File(FilePAth);
return mediaFile;
}
/*private String SaveImage_Sta(Bitmap finalBitmap, String name) {
if (isSDPresent) {
Log.i("isSDPresent yes", " path is==> " + isSDPresent);
String root = Environment.getExternalStorageDirectory().toString()
+ "/profile";
File myDir = new File(root);
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = name + ".jpg";
file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Log.i("isSDPresent no ", " path is==> false ");
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
file = new File(directory, "profile.jpg");
if (file.exists())
file.delete();
try {
FileOutputStream fos = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return file.toString();
}*/
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
if (ImageType.equals("AddPicture")) {
Intent i = new Intent(getBaseContext(),
MarketPlaceActivity.class);
i.putExtra("data", data);
startActivity(i);
} else {
Intent returnIntent = new Intent();
returnIntent.putExtra("data", data);
setResult(RESULT_OK, returnIntent);
CameraActivity.this.finish();
}
// mCamera.startPreview();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
public void onBackPressed() {
Intent returnIntent = new Intent();
returnIntent.putExtra("path", FilePAth);
setResult(RESULT_OK, returnIntent);
finish();
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
Log.v("log", " picturePath --> selected Gallary Image path --> "
+ picturePath);
cursor.close();
InputStream iStream;
byte[] inputData = null;
try {
iStream = getContentResolver().openInputStream(selectedImage);
inputData = getBytes(iStream);
Log.v("log", " selected Gallary Image ByteArray --> "
+ inputData);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (ImageType.equals("AddPicture")) {
Intent i = new Intent(getBaseContext(),
MarketPlaceActivity.class);
i.putExtra("data", inputData);
i.putExtra("image_from", "Gallary");
startActivity(i);
} else {
Intent returnIntent = new Intent();
returnIntent.putExtra("data", inputData);
returnIntent.putExtra("image_from", "Gallary");
setResult(RESULT_OK, returnIntent);
CameraActivity.this.finish();
}
// ImageView imageView = (ImageView) findViewById(R.id.imgView);
// imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
}
As I said in my comment, Android 4.4 (KitKat) has changed how permissions are handled on the SD card. It is now best practice to make your own directory on the SD card to handle all files your app needs to write. Right now you are trying to access the Pictures folder which is not owned or created by your app. Change your getOutputMediaFile() contents to this:
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/MyCameraApp/");
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdir();
}
return mediaStorageDir;
}

Image capturing in android is working only on emulator not in phone

I have followed this
to take an image using android inbuilt camera and save the image in sd card. The code is working fine with the emulator. But when i installed the apk in phone(samsung galaxy s3). the application will not take images.
My code is follows. Please have a look.
public class MainActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
protected Context context = this;
public static int count = 0;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
protected static final String TAG = "MyCameraAppss";
private Camera autoCam ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
captureImage();
}
});
}
private void captureImage(){
//Detecting camera hardware
boolean isCameraAvailable = checkCameraHardware(context);
if(isCameraAvailable){
Toast.makeText(context, "Camera found", Toast.LENGTH_SHORT).show();
//Accessing cameras
autoCam = getCameraInstance();
if(autoCam!=null){
autoCam.open();
Toast.makeText(context, "Camera is accesses successfully", Toast.LENGTH_SHORT).show();
autoCam.takePicture(null, null, mPicture);
Toast.makeText(context, "picture is taken and going to sleep for a sec", Toast.LENGTH_SHORT).show();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Toast.makeText(context, "Camera instance not available", Toast.LENGTH_SHORT).show();
}
Toast.makeText(context, "After slept going to release the camera", Toast.LENGTH_SHORT).show();
autoCam.release();
Toast.makeText(context, "Camera released successfully", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "cannot access the camera", Toast.LENGTH_SHORT).show();
}
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Toast.makeText(context, "Error creating media file, check storage permissions:", Toast.LENGTH_SHORT).show();
Log.d(TAG, "Error creating media file, check storage permissions: ");
return;
}else{
Toast.makeText(context, "Save: Pic file is found going to write", Toast.LENGTH_SHORT).show();
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast.makeText(context, "Save: Pic is saved successfully", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Toast.makeText(context, "File not found: " + e.getMessage(), Toast.LENGTH_LONG).show();
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Toast.makeText(context, "Error accessing file: " + e.getMessage(), Toast.LENGTH_LONG).show();
Log.d(TAG, "Error accessing file: " + e.getMessage());
}catch (Exception e) {
Toast.makeText(context, "Other Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
};
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
e.printStackTrace();
}
return c; // returns null if camera is unavailable
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp+"Amith" + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
The image is saved in the location
I have installed the apk on my phone and clicks the camera button mentioned in the first image, only "camera released toast" is displayed.
Is it necessary to load preview in our page?
i am very new with camera API.
Please guide me to resolve this
Thank you
This is my own blog here you will get description of your problem.
http://uniqueandroidtutorials.blogspot.in/2013/02/code-to-start-camera-with-build-in.html
Hope it will helps you..Thanks
Did you add this permission to AndroidManifest.xml file
<uses-feature android:name="android.hardware.camera" />
Then refer this codes. It work for me.
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri;
private static int RESULT_LOAD_IMAGE = 1;
public void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
if(latlon==null)
latlon="";
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "CERS");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath()+ File.separator+ timeStamp + "_--"+ latlon +"--.jpg");
}
return mediaFile;
}
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
IMGS.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
toast.ShowAlert("User cancelled image capture", 0,false);
} else {
// failed to capture image
toast.ShowAlert("Sorry! Failed to capture image",0,false);
}
}
/***/
/** Browse Images **/
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(picturePath, options);
IMGS.setImageBitmap(bitmap);
}
}

Not able to save Camera Images in Android

I am trying to save a image from camera. but its not working ..
Given permission
Code is pasted below. Not sure why its is not saving the image Code seems fine taken from developer.android site . Please help!
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
private Display display;
private int PreviewSizeWidth = 640;
private int PreviewSizeHeight= 480;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera,getWindowManager().getDefaultDisplay());
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
Button captureButton = (Button) findViewById(R.id.button1);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
Log.d("Take","Picture");
mCamera.takePicture(null, null, mPicture);
// mCamera.stopPreview();
// mCamera.startPreview();
}
}
);
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.d("TAG","Callabaclk start");
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);;
if (pictureFile == null){
Log.d("TAG", "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
Log.d("Ok",pictureFile.getAbsolutePath());
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,data.length);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
//fos.write(data);
fos.flush();
fos.close();
Log.d("TAG","DONE");
} catch (FileNotFoundException e) {
Log.d("Test", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Test", "Error accessing file: " + e.getMessage());
}
}
};
public static Camera getCameraInstance(){
Camera c = null;
try {
Log.d("Test",Camera.getNumberOfCameras()+"");
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
Log.d("test", e.toString());
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
public static boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
// File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
// Environment.DIRECTORY_PICTURES), "MyCameraApp");
File sampleDir = Environment.getExternalStorageDirectory();
File mediaStorageDir = new File(sampleDir.getPath()+File.separator+"Path");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
mediaStorageDir.mkdirs();
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
// mediaFile = new File(mediaStorageDir.getPath() + File.separator +"Path_"+ timeStamp + ".jpg");
mediaFile = new File(mediaStorageDir.getPath() ,"Path_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
When I do getPath() i get 08-14 02:31:52.153: D/Ok(4279): /storage/emulated/0/Path/Path_20130814_023152.jpg
After heck lot of research found it need to add these lines after fos.close :
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "Path");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ mediaStorageDir)));
Thanks
Njoy
check permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
try to create a simple file
String path = Environment.getExternalStorageDirectory() + "/" + "test.jpg";
File file = new File(path);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Then verify whether you can save your picture

Retrieving pixel array from image taken with a camera

I am working on an app that needs to access an array of pixels from a picture after it is taken. The main Activity is below. I have a good amount of java experience but extremely limited experience with images past displaying them on the screen. I see the byte array being passed to the picture callback method but I do not know how it is formatted. How can I get a pixel array that includes the RGB components from the captured image? I tried to find this through the stack overflow forums however I got a few hundred pages of results and only searched through the first 10 or so, so I am sorry if that has already been asked and I just did not see it.
public class ConverterActivity extends Activity
{
private Camera mCamera;
private CameraPreview mPreview;
private PictureCallback mPicture = new PictureCallback() {
private String TAG;
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
// Log.d(TAG, "Error creating media file, check storage permissions: " +
// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
// Create an instance of Camera
mCamera = Camera.open(this.getBackCamera());
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
}
#Override
protected void onPause()
{
super.onPause();
releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
public int getBackCamera()
{
int numCameras = Camera.getNumberOfCameras();
CameraInfo cInfo = new CameraInfo();
for (int i = 0; i < numCameras; i++)
{
Camera.getCameraInfo(i, cInfo);
if (cInfo.facing == CameraInfo.CAMERA_FACING_BACK)
{
return i;
}
}
return -1;
}
}
If you take the picture using code like this:
imgFile = new File(Environment.getExternalStorageDirectory () + "/somefolder/" + name + ".jpg");
String fileName = imgFile.getAbsolutePath();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(fileName)));
startActivityForResult(intent, REQUEST_FROM_CAMERA);
Then you should be able to, when you get the result back from this intent, using code like this to access the bitmap
if (imgFile.exists()) {
String fileName = file.getAbsolutePath();
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm;
opts.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(fileName, opts);
return bm;
}
else return null;
Then you can use bitmapfactory tools, such as compress to stream and then
convert to byte[]
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, stream); // 100 = max quality
byte[] byteArray = stream.toByteArray();

Categories

Resources