Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

java - screenshot saving as autogenerated file name

I made a button to take the screenshot and save into Pictures folder. I set it as being saved under the name capture.jpeg but I wanted it to be saved as such as cafe001.jpeg, cafe002.jpeg like this. Also would you please let me know how I can save it as time format.jpeg ? Thank you for your help in advance

container = (LinearLayout) findViewById(R.id.LinearLayout1);
        Button captureButton = (Button) findViewById(R.id.captureButton);
        captureButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            container.buildDrawingCache();
            Bitmap captureView = container.getDrawingCache();
            FileOutputStream fos;
            try {
                fos = new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + "capture.jpeg");
                captureView.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            Toast.makeText(getApplicationContext(),
                    "Captured under Pictures drectory", Toast.LENGTH_LONG)
                    .show();
        }
    });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To save as another name just change the string "capture.jpeg"

If you want to have it as cafeXXX.jpeg (where XXX is a number) then you could do something like this (this method could potentially cause number overlaps however if files are deleted):

int count = 1;
File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File[] content = picturesDir.listFiles();
for (File f: content)
{
    if (f.getName().matches("cafe\d+\.jpeg"))
        count++;
}
//... your other code
// if leading zeros important then add formatting code to the count
fos = new FileOutputStream(picturesDir.toString() + "cafe"+count+".jpeg");

If you want a timeformat just use SimpleDateFormat changing the format String as required (as only going to day will mean you will only get time format per day)

String timeFileName = new SimpleDateFormat("yyyy-MM-dd").format(new Date())
//...other code
fos = new FileOutputStream(picturesDir.toString() + timeFileName+".jpeg");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...