1

I am trying to save multiple images in a particular folder first image is saving correctly but the next one just replaces the first one. How to save multiple images? How to give the name dynamically and save the images with same name but with a different extension like image,image1,image2...etc Below is my code

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

    }
  • You need to save to a different file name if you want to accumulate a bunch of different images. Try automatically generating a unique file name for each save operation. – Mapsy Jun 13 '16 at 14:16

3 Answers3

1

You could use a counter variable in your Activity:

int counter = 0;

Append it in your file name and increment it after a successful save:

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

You should use some sort of persistent storage to store the current value of the counter, such as SharedPreferences.

Or, instead of a counter you could just use some unique identifier, System.currentTimeMillis for example, so you don't have to deal with keeping track of the values.

earthw0rmjim
  • 17,394
  • 8
  • 45
  • 61
0

set the timestamp as ImageName so everytime it will save with different Name..

for add timestamp refer :here

Community
  • 1
  • 1
Uttam Panchasara
  • 5,010
  • 4
  • 23
  • 38
0

Using recursive call, it can be achieved easily. Below is the code.

/**
 * 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
}

And call it like this in your code.

savePdf(directoryPath, fileName)
Shahbaz Hashmi
  • 2,133
  • 2
  • 18
  • 44