Android Application : display image - android

i'm working on a android application and I have to take a picture and save it. It's working and my picture is saved in a directory of the phone. Especially, in Picture directory.
So, here its my class parameter with the button to launch the camera ( new activity) and take the picture :
public class Parametre extends Activity {
private EditText ETpseudo= null;
private Button buttonPhoto = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parametres);
ETpseudo =(EditText) findViewById(R.id.editPseudo);
buttonPhoto = (Button) findViewById(R.id.buttonPhoto);
//ivPhoto.setImageBitmap();
buttonPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Parametre.this, CameraActivity.class));
}
});
}
}
CameraActivity :
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
private ImageView cadrePhoto = null;
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
Log.d("DEBUG", String.valueOf(grantResults[0]));
startCamera();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
Button captureButton = (Button) findViewById(R.id.button_capture);
startCamera();
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
}
private void startCamera(){
mCamera = getCameraInstance();
mCamera.startPreview();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
setCameraDisplayOrientation(this, 1, mCamera);
}
/**
* Helper method to access the camera returns null if it cannot get the
* camera or does not exist
*
* #return
*/
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open(1);
} catch (Exception e) {
e.printStackTrace();
}
return camera;
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void setCameraDisplayOrientation(Activity activity, int cameraId,android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d("Error", "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("DBG", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Error", "Error accessing file: " + e.getMessage());
}
}
};
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;
}
}
So, after taking the photo, I want to display the image on an ImageView in the parameter view. But I dont know how to do this. How to get back the photo and display him on the parameter View ?
Thanks.
Sorry for my english :/

you can do this in as easy way just create an static bitmap when picture taken in picturecallback method
Bitmap bmap=BitmapFactory.decodeByteArray(data, 0, data.length,sizeOptions);
Log.e("clickedbitmaaapp", String.valueOf(bmap));
static Bitmap mBitmap=bmap;
create this bitmap in other class which where you can access this easily.

Thanks you.
I can't test my code now. But do you think that should work here ? :
(cameraActivity)
public class CameraActivity extends Activity {
static Bitmap mBitmap;
...
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d("Error", "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bmap= BitmapFactory.decodeByteArray(data, 0, data.length, options);
mBitmap = bmap;
} catch (FileNotFoundException e) {
Log.d("DBG", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Error", "Error accessing file: " + e.getMessage());
}
}
};
and then in my parameter class :
public class Parametre extends Activity {
private EditText ETpseudo= null;
private Button buttonPhoto = null;
private ImageView iv = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parametres);
ETpseudo =(EditText) findViewById(R.id.editPseudo);
buttonPhoto = (Button) findViewById(R.id.buttonPhoto);
//ivPhoto.setImageBitmap();
buttonPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Parametre.this, CameraActivity.class));
}
});
ImageView imageView=(ImageView)findViewById(R.id.cadreImage);
imageView.setImageBitmap(CameraActivity.mBitmap);
}
}

Related

Camera Preview Android

I'm developing an Android App that has a Camera Preview Activity. It calls takePicture() every 2 second using a timer and does some processing on the captured image in PictureCallback. From the Android documentation, I learnt that PictureCallback happens in the same thread as Camera.open().
Also, it's recommended to call takePicture() in a separate thread. What's the best way to call StartPreview() after an image is captured?
I would want the processing on each capture to happen on separate threads and the camera preview should continue in the main UI thread. What's the best way to implement this using AsyncTask()?
public class CameraActivity extends AppCompatActivity{
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
public static String TAG = "Exception";
int viewWidth = 0;
int viewHeight = 0;
private Camera mCamera;
private CameraPreview mPreview;
private ImageView iv;
private RelativeLayout rl;
private Camera.PictureCallback mPicture;
private MRZ_OCR mrz = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
rl = (RelativeLayout) findViewById(R.id.rel_camera);
iv = (ImageView) findViewById(R.id.black_above);
viewWidth = iv.getWidth();
viewHeight = rl.getHeight() - 2 * iv.getHeight();
// Create an instance of Camera
mCamera = getCameraInstance();
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
new Timer().schedule(new TimerTask() {
#Override
public void run() {
mCamera.startPreview();
mrz = new MRZ_OCR();
mrz.execute();
}
}, 4000, 4000);
mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// Crop to get only MRZ
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
bm = Bitmap.createBitmap(bm, 0, pxFromDp(CameraActivity.this, 120), viewWidth, viewHeight);
//Verify if it has MRZ
bm = MRZ.getMRZ(bm);
if (bm != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
createImageFile(byteArray);
Toast.makeText(getApplicationContext(), "Pic Saved", Toast.LENGTH_LONG).show();
}
}
};
}
#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;
}
}
private class MRZ_OCR extends AsyncTask<Void, Void, Void>
{
private byte[] data;
#Override
protected Void doInBackground(Void... params) {
mCamera.takePicture(null, null, mPicture);
// Sleep for however long, you could store this in a variable and
// have it updated by a menu item which the user selects.
try {
Thread.sleep(3000); // 3 second preview
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// This returns the preview back to the live camera feed
mCamera.startPreview();
}
}
public static int pxFromDp(final Context context, final float dp) {
return (int) (dp * context.getResources().getDisplayMetrics().density);
}
/**
* 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)
}
return c; // returns null if camera is unavailable
}
private static File getOutputMediaFile(int type)
{
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// 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;
}
private static void createImageFile(byte[] byteArray) {
//create empty image type file
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);
fos.write(byteArray);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
}
I don't know about the api takePicture(),but i think what you need to do is put this code in a separate thread.
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
bm = Bitmap.createBitmap(bm, 0, pxFromDp(CameraActivity.this, 120), viewWidth, viewHeight);
//Verify if it has MRZ
bm = MRZ.getMRZ(bm);
if (bm != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
createImageFile(byteArray);
}
decodeBitmap is a time-consuming process, especially in you app,performed once every 2 seconds. it will blocking the main thread. and why it's recommended to call takePicture() in a separate thread, I think it is the same reason.
You already answered your question. Pass byte[] data to an AsyncTask:
private class PictureConverter extends AsyncTask<Void, Void, Void> {
private byte[] data;
private Camera camera;
public PictureConverter(byte[] _data, Camera _camera) {
data = _data;
camera = _camera;
}
protected Void doInBackground(Void... data) {
Camera.Parameters parameters = camera.getParameters();
ByteArrayOutputStream out = new ByteArrayOutputStream();
YuvImage yuvImage = new YuvImage(data, parameters.getPreviewFormat(), parameters.getPreviewSize().width, parameters.getPreviewSize().height, null);
yuvImage.compressToJpeg(new Rect(0, 0, parameters.getPreviewSize().width, parameters.getPreviewSize().height), 90, out);
byte[] imageBytes = out.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
out.flush();
out.close();
//TODO save the image
return null;
}
protected void onProgressUpdate() {
}
protected void onPostExecute() {
//TODO report that the image got saved
}
}

take picture continuously in android

I am new to android. I just downloaded an example camera program. I can take one image each time I click the "capture" button.
Now I want to know if it is possible to take two images continuously (one with flash and one without flash). Does anybody have a hint on how to do that? Thanks a lot.
I posted the sample code here:
public class AndroidCameraExample extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
private PictureCallback mPicture;
private Button capture, switchCamera;
private Context myContext;
private LinearLayout cameraPreview;
private boolean cameraFront = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
myContext = this;
initialize();
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
cameraFront = true;
break;
}
}
return cameraId;
}
private int findBackFacingCamera() {
int cameraId = -1;
//Search for the back facing camera
//get the number of cameras
int numberOfCameras = Camera.getNumberOfCameras();
//for every camera check
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
cameraFront = false;
break;
}
}
return cameraId;
}
public void onResume() {
super.onResume();
if (!hasCamera(myContext)) {
Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
toast.show();
finish();
}
if (mCamera == null) {
//if the front facing camera does not exist
if (findFrontFacingCamera() < 0) {
Toast.makeText(this, "No front facing camera found.", Toast.LENGTH_LONG).show();
switchCamera.setVisibility(View.GONE);
}
mCamera = Camera.open(findBackFacingCamera());
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
public void initialize() {
cameraPreview = (LinearLayout) findViewById(R.id.camera_preview);
mPreview = new CameraPreview(myContext, mCamera);
cameraPreview.addView(mPreview);
capture = (Button) findViewById(R.id.button_capture);
capture.setOnClickListener(captrureListener);
switchCamera = (Button) findViewById(R.id.button_ChangeCamera);
switchCamera.setOnClickListener(switchCameraListener);
}
OnClickListener switchCameraListener = new OnClickListener() {
#Override
public void onClick(View v) {
//get the number of cameras
int camerasNumber = Camera.getNumberOfCameras();
if (camerasNumber > 1) {
//release the old camera instance
//switch camera, from the front and the back and vice versa
releaseCamera();
chooseCamera();
} else {
Toast toast = Toast.makeText(myContext, "Sorry, your phone has only one camera!", Toast.LENGTH_LONG);
toast.show();
}
}
};
public void chooseCamera() {
//if the camera preview is the front
if (cameraFront) {
int cameraId = findBackFacingCamera();
if (cameraId >= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
} else {
int cameraId = findFrontFacingCamera();
if (cameraId >= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
}
#Override
protected void onPause() {
super.onPause();
//when on Pause, release camera in order to be used from other applications
releaseCamera();
}
private boolean hasCamera(Context context) {
//check if the device has camera
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
private PictureCallback getPictureCallback() {
PictureCallback picture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
//make a new picture file
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
//write the file
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast toast = Toast.makeText(myContext, "Picture saved: " + pictureFile.getName(), Toast.LENGTH_LONG);
toast.show();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
//refresh camera to continue preview
mPreview.refreshCamera(mCamera);
}
};
return picture;
}
OnClickListener captrureListener = new OnClickListener() {
#Override
public void onClick(View v) {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
mCamera.setParameters(parameters);
mCamera.takePicture(null, null, mPicture);
}
};
//make picture and save to a folder
private static File getOutputMediaFile() {
//make a new file directory inside the "sdcard" folder
File mediaStorageDir = new File("/sdcard/", "JCG Camera");
//if this "JCGCamera folder does not exist
if (!mediaStorageDir.exists()) {
//if you cannot make this folder return
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
//take the current timeStamp
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
//and make a media file:
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
private void releaseCamera() {
// stop and release camera
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
}

Getting a black screen after save photo - Android Camera

I'm developing an application for Android that captures max fps and saves to the SD card.
The problem is that the saved photo is a black screen, and I can't understand why.
Can anyone tell me where is the problem?
The code where I do this:
public class PhotoFragment extends Fragment {
private Camera cam;
private CameraPreview camPreview;
private boolean recording = false;
private ArrayList<byte[]> fotos;
private ArrayList<String> tempos;
private Thread thread;
public PhotoFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_photofinish, container, false);
cam = getCameraInstance();
if(cam != null) {
cam.setDisplayOrientation(90);
// set Camera parameters
Camera.Parameters cameraParameters = cam.getParameters();
//set color efects to none
cameraParameters.setColorEffect(Camera.Parameters.EFFECT_NONE);
//set antibanding to none
if (cameraParameters.getAntibanding() != null) {
cameraParameters.setAntibanding(Camera.Parameters.ANTIBANDING_OFF);
}
// set white ballance
if (cameraParameters.getWhiteBalance() != null) {
cameraParameters.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_CLOUDY_DAYLIGHT);
}
//set flash
if (cameraParameters.getFlashMode() != null) {
cameraParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
}
//set zoom
if (cameraParameters.isZoomSupported()) {
cameraParameters.setZoom(0);
}
//set focus mode
cameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_INFINITY);
List<Size> sizes = cameraParameters.getSupportedPictureSizes();
Camera.Size size = sizes.get(0);
cameraParameters.setPictureSize(size.width, size.height);
cam.setParameters(cameraParameters);
fotos = new ArrayList<byte[]>();
tempos = new ArrayList<String>();
camPreview = new CameraPreview(this.getActivity(), cam);
FrameLayout preview = (FrameLayout) rootView.findViewById(R.id.camera_preview);
preview.addView(camPreview);
TextView startRecording = (TextView) rootView.findViewById(R.id.start_record_button);
startRecording.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
if(!recording)
{
recording = true;
Size previewSize = cam.getParameters().getPreviewSize();
int dataBufferSize=(int)(previewSize.height*previewSize.width*(ImageFormat.getBitsPerPixel(cam.getParameters().getPreviewFormat())/8.0));
thread.start();
cam.addCallbackBuffer(new byte[dataBufferSize]);
cam.addCallbackBuffer(new byte[dataBufferSize]);
cam.addCallbackBuffer(new byte[dataBufferSize]);
cam.setPreviewCallbackWithBuffer(new PreviewCallback() {
public void onPreviewFrame(byte[] imageData, Camera arg1) {
try {
fotos.add(imageData);
tempos.add(new SimpleDateFormat("HH_mm_ss_SSS", Locale.getDefault()).format(new Date()));
} catch(Exception e) {
System.out.println("ERRO: " + e);
}
}
});
}
else
{
recording = false;
try {
thread.join();
} catch (Exception e) {
}
}
}
});
thread = new Thread(new Runnable() {
public void run() {
while(recording) {
if(fotos.size()>0 && tempos.size()>0)
{
File pictureFile = getOutputMediaFile(1, tempos.get(0));
if (pictureFile == null){
System.out.println("Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(fotos.get(0));
fos.close();
pictureFile = null;
cam.addCallbackBuffer(fotos.get(0));
fotos.remove(0);
tempos.remove(0);
} catch (FileNotFoundException e) {
System.out.println("ERRO FILE NOT FOUND! : " + e);
} catch (IOException e) {
System.out.println("ERRO IOException!");
}
}
}
}
});
}
else
{
Toast.makeText(getActivity(), "Camera not available", Toast.LENGTH_LONG).show();
}
return rootView;
}
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open();
}
catch (Exception e){
}
return c;
}
#Override
public void onDestroyView() {
super.onDestroyView();
cam.release();
}
private static File getOutputMediaFile(int type, String timeStamp){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "L_P");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
System.out.println("L_P failed to create directory");
return null;
}
}
String timeStampDay = new SimpleDateFormat("ddMMyyyy", Locale.getDefault()).format(new Date());
new File(mediaStorageDir.getPath() + File.separator + timeStampDay).mkdirs();
File mediaFile;
if (type == 1){
mediaFile = new File(mediaStorageDir.getPath() + File.separator + timeStampDay + File.separator + "IMG_"+ timeStamp + ".jpg");
} else if(type == 2) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
You are claiming that the file is a JPEG. However, you have done nothing to convert the image to be a JPEG. Preview frames, by default, are not JPEG, but are in NV21 format. Use getSupportedPreviewFormats() to see if JPEG previews are possible, then use setPreviewFormat() to request JPEG previews.
And, as I noted in your previous question, do NOT have two threads working with an ArrayList. Also, do not have your background thread busy-wait looking constantly for an image to show up on an ArrayList. Use a LinkedBlockingQueue or something else that is thread-safe and allows the background thread to block while waiting for an image.

how to capture picture portrait mode set portrait mode?

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.

Out of memory Error when previewing image in android

I have a custom camera application. When capture a image the application crashes. It should look like when capture then the image will preview on the screen but it crashes(Out of memory error). There are two activity (one is CustomCamera activity with two buttons and Preview activity with two buttons).
Here is my CustomCameraActivity:
public class CustomCameraActivity extends Activity implements
SurfaceHolder.Callback {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
context = this;
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mOrientaion1 = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
imageView = (ImageView) findViewById(R.id.imgError);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.custom, null);
LayoutParams layoutParamsControl = new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
Button btn1 = (Button) viewControl.findViewById(R.id.Button01);
Button btn2 = (Button) viewControl.findViewById(R.id.Button02);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Toast.makeText(context, "1111111111111111111111111",
// Toast.LENGTH_SHORT).show();
camera.takePicture(null, null, mPicture);
Constant.rotationValueForCamera = Constant.rotationValue;
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Toast.makeText(context, "22222222222222222222222222",
// Toast.LENGTH_SHORT).show();
Log.e("0 imagePickerStatus", Constant.imagePickerStatus + "");
Constant.imagePickerStatus = 0;
Log.e("0 imagePickerStatus", Constant.imagePickerStatus + "");
finish();
}
});
this.addContentView(viewControl, layoutParamsControl);
int ot = getResources().getConfiguration().orientation;
if (Configuration.ORIENTATION_LANDSCAPE == ot) {
imageView.setVisibility(View.GONE);
Log.e("ori1111", "land");
} else {
imageView.setVisibility(View.VISIBLE);
Log.e("ori111", "port");
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
// Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
findViewById(R.id.Button01).setVisibility(View.VISIBLE);
findViewById(R.id.Button02).setVisibility(View.VISIBLE);
imageView.setVisibility(View.GONE);
Log.e("ori", "land");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
// Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
findViewById(R.id.Button01).setVisibility(View.INVISIBLE);
findViewById(R.id.Button02).setVisibility(View.INVISIBLE);
imageView.setVisibility(View.VISIBLE);
Log.e("ori", "port");
}
}
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener);
}
#Override
public void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(sensorEventListener,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(sensorEventListener,
sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_NORMAL);
if (Constant.isCapturedOk) {
Constant.isCapturedOk = false;
finish();
}
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.e("Camrera", "22222222222222222");
Intent intent = new Intent(context, PreviewActivity.class);
// intent.putExtra("data", data);
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(data, 0,
data.length);
Matrix matrix = new Matrix();
if (Constant.result == 180) {
matrix.postRotate(270);
}
if (Constant.result == 270) {
matrix.postRotate(180);
}
int height = bitmapPicture.getHeight();
int width = bitmapPicture.getWidth();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmapPicture,
height, width, true);
Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
true);
ByteArrayOutputStream blob = new ByteArrayOutputStream();
rotatedBitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, blob);
byte[] bitmapdata = blob.toByteArray();
Constant.imageData = bitmapdata;
startActivity(intent);
}
};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if (previewing) {
camera.stopPreview();
previewing = false;
}
if (camera != null) {
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
setCameraDisplayOrientation(this,cameraId,camera);
previewing = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
Constant.result = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
Constant.result = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
Constant.result = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
Constant.result = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
#Override
protected void onStop() {
super.onStop();
Log.e("Tab", "Stoping");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Here is my Preview Activity:
public class PreviewActivity extends Activity {
Context context;
Button btnRetake, btnOk;
// byte[] data;
ImageView imgPreview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.preview_layout);
context = this;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
btnRetake = (Button) findViewById(R.id.btn1FromPreviw);
btnOk = (Button) findViewById(R.id.btn2FromPreviw);
imgPreview = (ImageView) findViewById(R.id.imgImagePreview);
// Intent myIntent = getIntent();
// data = myIntent.getExtras().getByteArray("data");
Drawable image = null;
image = new BitmapDrawable(BitmapFactory.decodeByteArray(
Constant.imageData, 0, Constant.imageData.length));
imgPreview.setBackgroundDrawable(image);
// image = new BitmapDrawable(Constant.imageData);
// imgPreview.setBackgroundDrawable(image);
btnRetake.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Constant.isCapturedOk = false;
finish();
}
});
btnOk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SaveImage();
}
});
}
private void SaveImage() {
/*
* File pictureFile = getOutputMediaFile(); if (pictureFile == null) {
* Log.e("Camrera", "nullllllllllllllllll"); return; }
*/
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(Constant.imageData , 0, Constant.imageData.length);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG ,50 , stream);
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Android" + File.separator + "data"
+ File.separator + context.getPackageName()
+ File.separator + "files" + File.separator + "image.jpg");
Log.e("pa", file.getPath() + " : " + file.getAbsolutePath());
Log.e("len", stream.size() + "");
file.createNewFile();
/*
* Log.e("Camrera", "yesssssssssssssssssss"); Log.e("Camrera",
* pictureFile.getAbsolutePath());
*/
FileOutputStream fos = new FileOutputStream(file);
fos.write(stream.toByteArray());
fos.close();
Log.e("Camrera", "great");
Constant.isCapturedOk = true;
Log.e("1 imagePickerStatus", Constant.imagePickerStatus + "");
Constant.imagePickerStatus = 1;
Log.e("1 imagePickerStatus", Constant.imagePickerStatus + "");
finish();
} catch (FileNotFoundException e) {
Log.e("mPicture FileNotFoundException", e.toString());
} catch (IOException e) {
Log.e("mPicture IOException", e.toString());
}
}
private File getOutputMediaFile() {
File mediaFile = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Android" + File.separator + "data"
+ File.separator + context.getPackageName() + File.separator
+ "files" + File.separator + "image.jpg");
return mediaFile;
}
#Override
protected void onStop() {
super.onStop();
Log.e("Tab", "Stoping");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Help me.
Can have a look on this
http://developer.android.com/training/displaying-bitmaps/index.html
Strange out of memory issue while loading an image to a Bitmap object
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap preview_bitmap=BitmapFactory.decodeStream(is,null,options);

Categories

Resources