How to send multiple images to another activity in android? - android

In my application i have created a custom camera where it captures images and save it in sd card. And also can view it in second activity. But it just replaces the previous images which i dont want. How to send multiple images to second activity?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.surfaceview);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
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);
this.addContentView(viewControl, layoutParamsControl);
click = (Button) findViewById(R.id.button_capture);
click.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
}});
}
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
filepath = Environment.getExternalStorageDirectory()+"/testing/"+"test.3gp";
System.out.println("thumbnail path~~~~~~"+filepath);
File file = new File(filepath);
Uri uriTarget = Uri.fromFile(file);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(CustomCameraActivity.this, "Image saved: " + uriTarget.toString(), Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("result",filepath.toString());
setResult(1,returnIntent);
finish();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// camera.startPreview();
}};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}

Just Convert your image into bitmap and pass that Bitmap in another activity by yourIntent.putExra("key",bitmap);
Or Use this:
private File imageFile;
private Uri imageUri;
private static final int CAMERA_REQUEST_CODE = 100;
private String imagePath
private Uri getTempUri() {
// Create an image file name
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String dt = sdf.format(new Date());
imageFile = null;
imageFile = new File(Environment.getExternalStorageDirectory()
+ "/foldername/", "Camera_" + dt + ".jpg");
Applog.Log(
TAG,
"New Camera Image Path:- "
+ Environment.getExternalStorageDirectory()
+ "/foldername/" + "Camera_" + dt + ".jpg");
File file = new File(Environment.getExternalStorageDirectory()
+ "/foldername");
if (!file.exists()) {
file.mkdir();
}
if (!imageFile.exists()) {
try {
imageFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
imagePath = Environment.getExternalStorageDirectory() + "/foldername/"
+ "Camera_" + dt + ".jpg";
imageUri = Uri.fromFile(imageFile);
return imageUri;
}
Now When you start activty for camera.
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(
MediaStore.EXTRA_OUTPUT,
getTempUri());
startActivityForResult(cameraIntent,
CAMERA_REQUEST_CODE);
Now In ActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (CAMERA_REQUEST_CODE == requestCode && resultCode == RESULT_OK) {
String yourUri=ImagePath;
//now store this Uri it will contain capture image url.
}
}

Related

Android Application : display image

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);
}
}

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;
}

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.

photo striped / scratched (the thumbnail view perfect)

My application capture and save a photo in a specific directory. The problem is when i go to the gallery to open the capture. The thumbnail view perfect, but when open the photo with HTC player the photo is striped / scratched.
I use an Activity that implements SurfaceHolder.Callback.
PictureCallback myJpeg = new PictureCallback() {
private boolean compress;
public void onPictureTaken(byte[] arg0, Camera arg1) {
File path = getPath();
File file = getName(path, imageNum);
imageNum ++;
try {
if(!path.exists())
path.mkdirs();
OutputStream imageFileOS = new FileOutputStream(file);
imageFileOS.write(arg0);
imageFileOS.close();
MediaScannerConnection.scanFile(getApplicationContext(),
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(imageNum < numDisp)
myCamera.startPreview();
else{
goToViewCapture(file);
}
}
};
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
try{
if(myPreviewRunning){
myCamera.stopPreview();
myPreviewRunning = false;
}
Camera.Parameters p = myCamera.getParameters();
p.setPreviewSize(width,height);
myCamera.setParameters(p);
myCamera.setPreviewDisplay(holder);
myCamera.startPreview();
myPreviewRunning = true;
}catch(Exception e){e.printStackTrace();}
}
public void surfaceCreated(SurfaceHolder holder) {
myCamera = Camera.open();
try {
Camera.Parameters parameters = myCamera.getParameters();
parameters.set("jpeg-quality", 70);
parameters.setPictureFormat(PixelFormat.JPEG);
myCamera.setParameters(parameters);
myCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
myCamera.release();
}
//myCamera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
myCamera.stopPreview();
myPreviewRunning = false;
myCamera.release();
myCamera = null;
}
Thanks!!!
SOLUTION:
comment this line --> //p.setPreviewSize(width,height);

Camera images being saved to sdcard as empty files?

I was wondering if any1 could tell me why my photos are being saved with a size of 0kb meaning that they are empty?... i checked my sd card and they are being saved but with nothing in them... heres the code
public class CameraAPI extends Activity implements SurfaceHolder.Callback{
public Camera camera;
MediaRecorder mediaRecorder;
CBDataBaseHelper RH;
TextView RecipeID;
Bitmap finalBitmap;
public void onCreate (Bundle savedInstanceState){
boolean diditwork;
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
RecipeID = (TextView)findViewById(R.id.Rid2);
String RowID;
Bundle extras = getIntent().getExtras();
RowID = extras.getString("SELECTED2");
RecipeID.setText(RowID);
SurfaceView surface = (SurfaceView)findViewById(R.id.acccam);
SurfaceHolder holder = surface.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}catch(Exception e){
diditwork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("darn");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}}
public void takePhoto(View view){
//String ID = RecipeID.getText().toString();
//Long LID = Long.parseLong(ID);
boolean diditwork;
try{
takePicture();
}catch(Exception e){
diditwork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("darn");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
//String path = "/sdcard/Image.jpg";
//RH.updateRecipe3(LID,path);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
if (mediaRecorder == null){
try{
camera = camera.open();
camera.setPreviewDisplay(holder);
camera.startPreview();
}catch (IOException e){
Log.d("CAMERA", e.getMessage());
}
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
}
public void takePicture(){
boolean diditwork;
try{
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}catch(Exception e){
diditwork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("darn");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
}
ShutterCallback shutterCallback= new ShutterCallback()
{
public void onShutter(){
}
};
PictureCallback rawCallback = new PictureCallback(){
public void onPictureTaken(byte[] data, Camera camera){
}
};
PictureCallback jpegCallback = new PictureCallback(){
public void onPictureTaken(byte[] data, Camera camera){
// FileOutputStream outStream = null;
boolean diditwork;
File myDir=new File("/sdcard");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "/Image"+ n +".jpg";
File 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();
}
RH = new CBDataBaseHelper(CameraAPI.this);
RH.open();
String ID = RecipeID.getText().toString();
Long RID = Long.parseLong(ID);
RH.updateRecipe3(RID, myDir +fname);
RH.close();
//String ID = RecipeID.getText().toString();
//Long RID = Long.parseLong(ID);
//RH.updateRecipe3(RID, myDir + fname);
}
};
}
thanks Stefan
Two things:
finalBitmap is never initialized, so I'd assume that you're catching a Null Pointer Error every time in the try catch block in the jpegCallback. You also aren't doing anything with the byte array passed to you in the callback, which means you aren't doing anything to save the image. Try doing the following in the beginning of onPictureTaken in jpegCallback:
finalBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
see BitmapFactory for more info
If your goal is to simply allow a user to take a picture and you don't care much about the details, by far the easiest thing to do is to use startActivityForResult and let the native camera app handle taking the picture and creating the file. If you need to use the image created afterward, you can pass in a Uri so that you know where the image will be saved. This has the added bonus of working with Android's MediaStore.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Uri is parcelable so you can save this to a bundle in onSaveInstanceState
//and retrieve it in onResume
photoUri = getActivity().getContentResolver().insert(EXTERNAL_CONTENT_URI, new ContentValues());
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
// Lanuch the activity
startActivityForResult(intent, TAKE_PHOTO);
You can then handle the result by implement onActivityResult(). See startActivityForResult

Categories

Resources