我创建了一个自定义相机,它可以拍摄照片并将其存储在手机内部存储器的文件夹中。但是每当我拍摄一张新照片时,它都会覆盖旧照片。
主要活动
public class MainActivity extends AppCompatActivity {
Camera camera;
Button capture, gallery;
FrameLayout frameLayout;
ShowCamera showCamera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = findViewById(R.id.frameLayout);
capture = findViewById(R.id.button);
gallery = findViewById(R.id.button2);
camera = Camera.open();
showCamera = new ShowCamera(this,camera);
frameLayout.addView(showCamera);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
captureImage(showCamera);
}
},4000);
}
Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File picture_file = getOutputMediaFile();
if(picture_file==null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(picture_file);
fos.write(data);
fos.close();
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
};
private File getOutputMediaFile() {
String state = Environment.getExternalStorageState();
if(!state.equals(Environment.MEDIA_MOUNTED)) {
return null;
}
else {
File folder_gui = new File (Environment.getExternalStorageDirectory() + File.separator+"GUI");
if(!folder_gui.exists()) {
folder_gui.mkdirs();
}
File outputFile = new File(folder_gui,"temp.jpg");
return outputFile;
}
}
public void captureImage(View v) {
if(camera!=null) {
camera.takePicture(null,null,mPictureCallback);
}
}
}
显示相机
public class ShowCamera extends SurfaceView implements SurfaceHolder.Callback{
Camera camera;
SurfaceHolder holder;
public ShowCamera(Context context, Camera camera) {
super(context);
this.camera = camera;
holder = getHolder();
holder.addCallback(this);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Camera.Parameters params = camera.getParameters();
//change the orientation of the camera
List<Camera.Size> sizes = params.getSupportedPictureSizes();
Camera.Size mSize = null;
for(Camera.Size size : sizes) {
mSize = size;
}
if(this.getResources().getConfiguration().orientation!= Configuration.ORIENTATION_LANDSCAPE) {
params.set("orientation","portrait");
camera.setDisplayOrientation(90);
params.setRotation(90);
}
else {
params.set("orientation","landscape");
camera.setDisplayOrientation(0);
params.setRotation(0);
}
params.setPictureSize(mSize.width,mSize.height);
camera.setParameters(params);
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
}
拍摄新图片时,我希望将该图片添加到文件夹中,而不是覆盖现有图片。我该怎么做呢?