I want to take a picture with my phone via an application and save the image on my phone.
I've tried many of the solutions proposed on the stackoverflow questions but it did not mark so I built a method that saves the file with the right name ... but the file is empty (0kb)!
Here is my code
public class GameActivity extends Activity implements SurfaceHolder.Callback/*,Camera.PictureCallback*/ {
private Camera camera;
private SurfaceView surfaceCamera;
public Handler handler = new Handler();
private boolean isPreview=false;
private SurfaceHolder holder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameactivity);
surfaceCamera = (SurfaceView) findViewById(R.id.surfaceViewCamera);
getWindow().setFormat(PixelFormat.UNKNOWN);
holder = surfaceCamera.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
ImageView image = (ImageView) findViewById(R.id.imageView3);
image.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
camera.takePicture(myShutterCallback, myPictureCallback_RAW, myPictureCallback_JPG);
return false;
}
Camera.ShutterCallback myShutterCallback = new Camera.ShutterCallback() {
public void onShutter() {
// TODO bl
}
};
PictureCallback myPictureCallback_RAW = new PictureCallback() {
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}
};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "/KersplattFolder");
imagesFolder.mkdirs();
String fileName = "image.jpg";
File output = new File(imagesFolder, fileName);
try {
FileOutputStream fos = new FileOutputStream(output);
fos.write(data[0]);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(GameActivity.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
camera.startPreview();
}
};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if (isPreview) {
camera.stopPreview();
}
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(width,height);
camera.setParameters(p);
try {
camera.setPreviewDisplay(holder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
isPreview=true;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
isPreview=false;
camera.release();
}
EDIT1 : when I put data instead of data[0] I save a black image as well but the file has a weight so I guess the real image is somewhere...
EDIT2
I have added the code
File output = new File(imagesFolder, fileName);
Uri outputFileUri = Uri.fromFile(output);
String filePath = outputFileUri.getPath();
File file= new File(filePath);
try {
FileOutputStream fos = new FileOutputStream(file,true);
fos.write(data);
fos.close();
}
Still have the black image
have you defined the required permissions in your Android manifest like described here?
<manifest ... >
<uses-feature android:name="android.hardware.camera" />
...
</manifest ... >
UPDATE:
Ok, remove the brackets after data: data instead of data[]. Then it should work.
Your code: fos.write(data[0]); is wrong. I am surprised that you did not get an exception
Here is the code I used to save the byte array after taking a picture. "data" is the byte array.
String filePath = outputFileUri.getPath(); // .getEncodedPath();
File file = new File(filePath);
FileOutputStream os;
try {
os = new FileOutputStream(file, true);
os.write(data);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
I Created a app that captures image and stores in the SD Card. The app seems to work fine with the previewing. But the problem is that when I run the app on my phone through eclipse the image gets captured. If I run my app in a normal way and try to capture the image, the image doesn't get captured.
I have attached my code below
My MainActivity.class
public class MainActivity extends Activity {
private ImageHandler preview;
Camera camera;
int cameraID, currentCamera;
Button capture;
FrameLayout imageLayout;
SurfaceView imgl;
private static final String TAG = "CallCamera";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* Invoking Camera and Setting the ImageHandler for preview
*/
camera = getCameraInstance();
preview = new ImageHandler(this, camera);
/*
* Getting the ID of the FrameLayout that displays the camera
*/
imageLayout = (FrameLayout) findViewById(R.id.preview_layout);
imageLayout.addView(preview);
/*
* Getting the ID of capture Button and setting its Functionality
*/
capture = (Button) findViewById(R.id.cameraButton);
capture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(null, null, null, pic);
}
});
}
private Camera getCameraInstance() {
// TODO Auto-generated method stub
Camera cam = null;
try {
cam = Camera.open();
} catch (Exception e) {
}
return cam;
}
PictureCallback pic = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
// File picFile = getOutputPhotoFile();
// if(picFile == null){
// return;
// }
//
// try{
// FileOutputStream fos = new FileOutputStream(picFile);
// fos.write(data);
// fos.close();
//
// }catch(FileNotFoundException e){
//
// }catch (IOException e){
//
// }
//
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
Log.d(TAG, "Can't create directory to save image.");
Toast.makeText(getApplicationContext(),
"Can't create directory to save image.",
Toast.LENGTH_LONG).show();
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "Picture_" + date + ".jpg";
String filename = pictureFileDir.getPath() + File.separator
+ photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast.makeText(getApplicationContext(),
"New Image saved:" + photoFile, Toast.LENGTH_LONG)
.show();
} catch (Exception error) {
Log.d(TAG,
"File" + filename + "not saved: " + error.getMessage());
Toast.makeText(getApplicationContext(),
"Image could not be saved.", Toast.LENGTH_LONG).show();
}
camera.startPreview();
}
private File getDir() {
File sdDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "CameraAPIDemo");
}
};
// private File getOutputPhotoFile() {
//
// File directory = new File(
// Environment
// .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
// "IMAGES_CAMERA");
//
// if (!directory.exists()) {
// if (!directory.mkdirs()) {
// Log.e(TAG, "Failed to create storage directory.");
// return null;
// }
// }
//
// String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss")
// .format(new Date());
//
// return new File(directory.getPath() + File.separator + "IMG_"
// + timeStamp + ".jpg");
// }
//
#Override
public void onResume() {
super.onResume();
if (camera == null) {
camera = Camera.open();
preview.setCamera(camera);
}
}
}
My Preview/ ImageHandler.class
public class ImageHandler extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holder;
private Camera imgCamera;
List<Size> imgSupportedPreviewSizes;
public ImageHandler(Context context, Camera camera) {
super(context);
// TODO Auto-generated constructor stub
this.imgCamera = camera;
this.holder = this.getHolder();
this.holder.addCallback(this);
this.holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
try {
imgCamera.setPreviewDisplay(holder);
imgCamera.startPreview();
} catch (IOException e) {
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
try {
imgCamera.setPreviewDisplay(holder);
imgCamera.startPreview();
imgCamera.setDisplayOrientation(90);
} catch (Exception e) {
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
imgCamera.stopPreview();
imgCamera.release();
}
public void setCamera(Camera camera) {
imgCamera = camera;
if (imgCamera != null) {
imgSupportedPreviewSizes = imgCamera.getParameters()
.getSupportedPreviewSizes();
requestLayout();
}
}
}
I want to be able to capture image when I run the app normally through my phone.
I need to use camera without preview and take more than one shots.
I have written my code and I am able to take one shot, it works properly.
But I could not handle to do more than once. Because the logic of Camera Service i tried a method CreateCameraTakeShot, still no success.
Could you please help me with that?
Here is my code;
public class ContinuingCallActivity extends Activity implements SurfaceHolder.Callback{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
FileOutputStream outStream;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_continuingcall);
//getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceView1);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// for(int i=0;i<10;i++)
//{
mHandler.postDelayed(mLaunchTask, 1000);
//}
}
Handler mHandler = new Handler();
private Runnable mLaunchTask = new Runnable() {
#Override
public void run() {
camera.takePicture(null,myPictureCallback_RAW, myPictureCallback_JPG);
//createCameraTakeShot();
}
};
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);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/MySight/";
File newdir = new File(dir);
newdir.mkdirs();
Date d = new Date();
CharSequence dateOfShot = DateFormat.format("dd-MM-yy hh:mm:ss", d.getTime());
String file = dir+dateOfShot+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
outStream = new FileOutputStream(newfile);
outStream.write(bytes.toByteArray());
outStream.close();
Log.d("Log", "onPictureTaken - wrote bytes: " + arg0.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
public void createCameraTakeShot()
{
camera = Camera.open();
if (camera != null)
{
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
camera.takePicture(null,myPictureCallback_RAW, myPictureCallback_JPG);
camera.stopPreview();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
//camera.release();
//camera = null;
previewing = false;
}
}
you can use timer task insted of handler to take picture prodically
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
surfaceView = (SurfaceView)findViewById(R.id.surfaceView1);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
MyTimerTask myTask = new MyTimerTask();
Timer myTimer = new Timer();
myTimer.schedule(myTask, 1000, 1000);
}
class MyTimerTask extends TimerTask {
public void run() {
// ERROR
camera.takePicture(null,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);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/MySight/";
File newdir = new File(dir);
newdir.mkdirs();
Date d = new Date();
CharSequence dateOfShot = DateFormat.format("dd-MM-yy hh:mm:ss", d.getTime());
String file = dir+dateOfShot+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
outStream = new FileOutputStream(newfile);
outStream.write(bytes.toByteArray());
outStream.close();
Log.d("Log", "onPictureTaken - wrote bytes: " + arg0.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
public void createCameraTakeShot()
{
camera = Camera.open();
if (camera != null)
{
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
camera.takePicture(null,myPictureCallback_RAW, myPictureCallback_JPG);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
//camera.release();
//camera = null;
previewing = false;
}
}
I’m a beginner and I need help. How do I take photos with camera and save or send to next activity?
I've tried a couple of options, i.e. takepicture with picture callback and surfaceview/take with intent. However, neither works properly on Android 2.3.3. Could someone figure out the issues with my code below?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sf_foto);
mCamera = getCameraInstance();
mCameraPreview = new SF_CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
ImageButton captureButton = (ImageButton) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(myShutterCallback, mPicture_RAW, mPicture);
}
});
}
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open(0);
camera.setDisplayOrientation(90);
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {}
};
PictureCallback mPicture_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {}
};
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.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Intent i = new Intent(StyloveFoto.this, Filter.class);
startActivity(i);
}
};
protected File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),"KWAlbum");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("KWAlbum", "failed to create directory");
return null;
}
}
// Create a media file name
File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "KW" + ".jpg");
return mediaFile;
}
my surface view:
public class SF_CameraPreview extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
public SF_CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
// left blank for now
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
//mCamera.stopPreview();
mCamera.release();
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
mCamera.setPreviewDisplay(surfaceHolder);
Camera.Parameters parameters = mCamera.getParameters();
parameters.set("orientation", "portrait");
mCamera.setParameters(parameters);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
}
instead of this line : fos.write(data);
write : fos.write(data,0,data.length);
if you want to pass it to the next activity:
Intent i = new Intent(StyloveFoto.this, Filter.class);
i.putExtra("myImage",data);
startActivity(i);
and then in class filter in the oncreate method
byte[] myImage = getIntent()getIntent().getByteArrayExtra("myImage");
I got the same problem and i just solve it before.
The problem is that mPicture is an object of PictureCallback. You can't set intent directing to Filter.class from StyloveFoto.this, because it is in PictureCallback interface. Try this one:
Intent i = new Intent(getBaseContext() , Filter.class);
startActivity(i);
Such a big trap in java....hope it helps :)
Either you save the picture like this and pass the path to another activity
final File file = new File(Environment.getExternalStorageDirectory() + "/" + System.currentTimeMillis() + "_pic.jpg");
OutputStream output = null;
try {
output = new FileOutputStream(file);
output.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != output) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
OR
Pass data from camera activity :
Intent intent = new Intent(getApplicationContext(), your_class.class);
intent.putExtra("path", path);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Receiving Activity
byte[] data = getIntent().getByteArrayExtra("path");
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
image.setImageBitmap(scaleDownBitmapImage(bitmap, 300, 200));
This is my code to take pictures in Android. But, it always return a blank image. What might be the error? I saw a few issues of setting the flash, exposure and focus mode which I set in my code but still the camera returns a blank image even though the photo gets taken.(Atleast I heard the sound of the aperture.)
C
amera.Parameters p = camera.getParameters();
List<Size> sizes = p.getSupportedPictureSizes();
// Choose any one you want among sizes
Size size = sizes.get(0);
p.setPictureSize(size.width, size.height);
p.set("flash-mode","off");
p.set("focus-mode","auto");
p.setExposureCompensation(100);
p.setFocusMode("auto");
camera.setParameters(p);
camera.startPreview();
camera.takePicture(shutterCallback, rawCallback,
jpegCallback);
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
// write to local sandbox file system
// outStream =
// CameraDemo.this.openFileOutput(String.format("%d.jpg",
// System.currentTimeMillis()), 0);
// Or write to sdcard
outStream = new FileOutputStream(String.format(
"/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
Paint p = new Paint(Color.RED);
Log.d(TAG, "draw");
canvas.drawText("PREVIEW", canvas.getWidth() / 2,
canvas.getHeight() / 2, p);
}
Camera.java
public class Camera extends Activity
{
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent cameraIntent = new Intent(ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
Random randomGenerator = new Random();randomGenerator.nextInt();
String newimagename=randomGenerator.toString()+".jpg";
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + newimagename);
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//write the bytes in file
try {
fo = new FileOutputStream(f.getAbsoluteFile());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
uri=f.getAbsolutePath();
//this is the url that where you are saved the image
}
}
UPDATE
Added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
to the manifest all works ok now.
Ok so I have a app I have started to create which in the end I want to be able to take a picture, which then takes you to another screen which lets you be able to "Use" or "Retake" the picture.
When the image is took it needs to be saved into a new folder on the SD Card, (if the folder is not there then it needs to create it). I had all this working a couple of weeks ago but after i did some editing and shut down eclipse I cant seem to get it back working?
The section for this is after int imageNum = 0; i have added imagesFolder.mkdirs(); which i belive is correct to create a new folder but even this seems not to be working now.
Now the image just gets took and neither the new folder gets created or the image gets saved.
public class AndroidCamera extends Activity implements SurfaceHolder.Callback {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
final int RESULT_SAVEIMAGE = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
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.control, null);
LayoutParams layoutParamsControl = new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
Button buttonTakePicture = (Button) findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback, myPictureCallback_RAW,
myPictureCallback_JPG);
}
});
}
ShutterCallback myShutterCallback = new ShutterCallback() {
public void onShutter() {
// TODO Auto-generated method stub
}
};
PictureCallback myPictureCallback_RAW = new PictureCallback() {
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}
};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
/*Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length); */
int imageNum = 0;
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "BeatEmUp");
imagesFolder.mkdirs();
String fileName = "image_" + String.valueOf(imageNum) + ".jpg";
File output = new File(imagesFolder, fileName);
while (output.exists()){
imageNum++;
fileName = "image_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}};
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if (previewing) {
camera.stopPreview();
previewing = false;
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
try {
Camera.Parameters parameters = camera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
// This is an undocumented although widely known feature
parameters.set("orientation", "portrait");
// For Android 2.2 and above
camera.setDisplayOrientation(90);
// Uncomment for Android 2.0 and above
parameters.setRotation(90);
} else {
// This is an undocumented although widely known feature
parameters.set("orientation", "landscape");
// For Android 2.2 and above
camera.setDisplayOrientation(0);
// Uncomment for Android 2.0 and above
parameters.setRotation(0);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
} catch (IOException exception) {
camera.release();
}
camera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
You should make sure the manifest lists the permission to write to the SD card:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />