我正在尝试在特定文件夹中保存多个图像第一个图像正确保存,但下一个图像只是替换第一个图像。如何保存多个图像?如何动态地给出名称并保存具有相同名称但具有不同扩展名的图像,如image,image1,image2等 以下是我的代码
public class CameraView extends Activity implements SurfaceHolder.Callback, OnClickListener{
private static final String TAG = "CameraTest";
Camera mCamera;
boolean mPreviewRunning = false;
@SuppressWarnings("deprecation")
public void onCreate(Bundle icicle){
super.onCreate(icicle);
Log.e(TAG, "onCreate");
getWindow().setFormat(PixelFormat.TRANSLUCENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.cameraview);
ImageView img = (ImageView) findViewById(R.id.blankImage);
if(ImageViewActivity.isBlack)
img.setBackgroundResource(android.R.color.black);
else
img.setBackgroundResource(android.R.color.white);
mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
mSurfaceView.setOnClickListener(this);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
}
private void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
private File getAlbumStorageDir(Context context, String albumName) {
// Get the directory for the app's private pictures directory.
File file = new File(context.getExternalFilesDir(
Environment.DIRECTORY_PICTURES), albumName);
if(file.exists()){
return null;
}
if (!file.mkdirs()) {
Log.e("MainActivity.error", "Directory not created");
}
return file;
}
Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
if (data != null){
//Intent mIntent = new Intent();
//mIntent.putExtra("image",imageData);
mCamera.stopPreview();
mPreviewRunning = false;
mCamera.release();
Bitmap resizedBitmap=null;
try{
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bitmap= BitmapFactory.decodeByteArray(data, 0, data.length,opts);
bitmap = Bitmap.createScaledBitmap(bitmap, 300, 300, false);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = 300;
int newHeight = 300;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(90);
resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
width, height, matrix, true);
ImageViewActivity.image.setImageBitmap(resizedBitmap);
}catch(Exception e){
e.printStackTrace();
}
//StoreByteImage(mContext, imageData, 50,"ImageName");
//setResult(FOTO_MODE, mIntent);
FileOutputStream out = null;
File picturesDir = getAlbumStorageDir(getBaseContext(), "myDirName");
File savedPic = new File(picturesDir.getAbsolutePath() + "/mynewpic.jpg");
try {
out = new FileOutputStream(savedPic);
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
copy(picturesDir, savedPic);
} catch (IOException e) {
Log.e("MainActivity.err", "failed to copy");
}
setResult(585);
finish();
}
}
};
protected void onResume(){
Log.e(TAG, "onResume");
super.onResume();
}
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
}
protected void onStop(){
Log.e(TAG, "onStop");
super.onStop();
}
@TargetApi(9)
public void surfaceCreated(SurfaceHolder holder){
Log.e(TAG, "surfaceCreated");
mCamera = Camera.open(ImageViewActivity.cameraID);
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
Log.e(TAG, "surfaceChanged");
// XXX stopPreview() will crash if preview is not running
if (mPreviewRunning){
mCamera.stopPreview();
}
Camera.Parameters p = mCamera.getParameters();
p.setPreviewSize(300, 300);
if(ImageViewActivity.cameraID == 0){
String stringFlashMode = p.getFlashMode();
if (stringFlashMode.equals("torch"))
p.setFlashMode("on"); // Light is set off, flash is set to normal 'on' mode
else
p.setFlashMode("torch");
}
/*mCamera.setParameters(p);*/
try{
mCamera.setPreviewDisplay(holder);
}catch (Exception e){
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.startPreview();
mPreviewRunning = true;
mCamera.takePicture(null, mPictureCallback, mPictureCallback);
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e(TAG, "surfaceDestroyed");
//mCamera.stopPreview();
//mPreviewRunning = false;
//mCamera.release();
}
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
public void onClick(View v) {
// TODO Auto-generated method stub
mCamera.takePicture(null, mPictureCallback, mPictureCallback);
}
}
答案 0 :(得分:1)
您可以在Activity
中使用计数器变量:
int counter = 0;
将其附加到您的文件名中,并在成功保存后递增:
File savedPic = new File(picturesDir.getAbsolutePath() + "/mynewpic" + counter + ".jpg");
try {
out = new FileOutputStream(savedPic);
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
counter++; // no exception thrown, increment the counter
} catch (Exception e) {
e.printStackTrace();
}
您应该使用某种持久性存储来存储计数器的当前值,例如SharedPreferences
。
或者,您可以使用一些唯一标识符System.currentTimeMillis
代替计数器,因此您无需处理跟踪值。
答案 1 :(得分:0)
将时间戳设置为ImageName,以便每次使用不同的名称保存时。
添加时间戳请参阅:here
答案 2 :(得分:0)
使用递归调用,可以轻松实现。下面是代码。
/**
* fileCount - to avoid overwrite and save file
* with order ie - test - (1).pdf, test - (2).pdf
*/
fun savePdf(directoryPath: String, fileName: String, fileCount: Int = 0) {
val newFileName = if (fileCount == 0) {
"$fileName.pdf"
} else {
"$fileName - ($fileCount).pdf"
}
val targetFilePath = File(directoryPath, newFileName)
if (targetFilePath.exists()) {
savePdf(directoryPath, fileName, fileCount + 1)
return
}
// add your logic to save file in targetFilePath
}
并在您的代码中这样称呼它。
savePdf(directoryPath, fileName)