将新图像保存在SD卡中而不是覆盖

时间:2016-09-12 10:14:10

标签: android canvas android-bitmap fileoutputstream

我创建了一个Android应用程序,我在屏幕上绘制并点击按钮它保存在图片文件夹中。

代码:

MainActivity

 package com.example.writeonscreen;

import android.support.v7.app.ActionBarActivity;
import android.util.AttributeSet;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;


public class WriteOnScreenActivity extends ActionBarActivity {
private String state;
Bitmap bmp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new TouchEventView(this,null));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.write_on_screen, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.savepic) {
            state=Environment.getExternalStorageState();
            if(state.equals(Environment.MEDIA_MOUNTED)){


                 String fileJPG = null;
                 final File path =
                            Environment.getExternalStoragePublicDirectory
                            (
                                //Environment.DIRECTORY_PICTURES
                                //Environment.DIRECTORY_DCIM
                                Environment.DIRECTORY_DCIM + "/Utkarshpic/"
                            );

                        // Make sure the Pictures directory exists.
                        if(!path.exists())
                        {
                            path.mkdirs();
                        }

                        final File file = new File(path, fileJPG + ".jpg");

                        try
                        {
                            final FileOutputStream fos = new FileOutputStream(file);
                            final BufferedOutputStream bos = new BufferedOutputStream(fos, 8192);

                            //bmp.compress(CompressFormat.JPEG, 100, bos);
                            bmp.compress(CompressFormat.JPEG, 85, bos);
Toast.makeText(getBaseContext(), "Picture saved in Utkarshpic", Toast.LENGTH_SHORT).show();
                            bos.flush();
                            bos.close();
                        }
                        catch (final IOException e)
                        {
                            e.printStackTrace();
                        }



            }else{
                Toast.makeText(getBaseContext(), "Cannot Save Image.No SD Card !", Toast.LENGTH_LONG).show();
            }

            return true;
        }
        return super.onOptionsItemSelected(item);
    }



    public class TouchEventView extends View {
        Paint paint=new Paint();
        Path path=new Path();
        Bitmap myBitmap;
    public TouchEventView(Context context, AttributeSet attrs) {
            super(context, attrs);
            // TODO Auto-generated constructor stub
            paint.setAntiAlias(true);
            paint.setColor(Color.BLUE);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(5);
        }
    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        canvas.drawPath(path, paint);
        myBitmap=Bitmap.createBitmap((int)canvas.getWidth(), (int)canvas.getHeight(), Config.ARGB_8888);// bitmap created
        canvas=new Canvas(myBitmap);

        canvas.drawARGB(255, 255, 255,255);
        canvas.drawPath(path, paint);
        pass(myBitmap);

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        float xPos=event.getX();
        float yPos=event.getY();
        switch(event.getAction()){
        case MotionEvent.ACTION_DOWN:
            path.moveTo(xPos, yPos);
            return true;
        case MotionEvent.ACTION_MOVE:
            path.lineTo(xPos, yPos);
            break;
        case MotionEvent.ACTION_UP:
            break;
            default:
                return false;

        }
        invalidate();

        return true;


    }


    }



    public void pass(Bitmap myBitmap) {
        // TODO Auto-generated method stub
        bmp=myBitmap;
    }

}

现在的问题是,每当我创建一个新画布并将其保存在SD卡中而不是创建一个具有唯一名称的新图片时,会覆盖之前保存的图片。

如何在我的文件夹中添加具有唯一名称的新图像保存?

4 个答案:

答案 0 :(得分:2)

只需更改以下代码行:

final File file = new File(path, fileJPG + ".jpg");

到此:

final File file = new File(path, fileJPG + "_" + System.currentTimeMillis() + ".jpg");

答案 1 :(得分:1)

对于每个新图像,您必须使用新名称保存图像。

例如:附加时间戳,如:

 final File file = new File(path, fileJPG + timestamp+".jpg");

答案 2 :(得分:1)

或以下代码将为您正在创建的文件创建唯一的随机名称:

   public static String generateUniqueFileName() {
        String filename = "";
        long millis = System.currentTimeMillis();
        String datetime = new Date().toGMTString();
        datetime = datetime.replace(" ", "");
        datetime = datetime.replace(":", "");
        String rndchars = RandomStringUtils.randomAlphanumeric(16);
        filename = rndchars + "_" + datetime + "_" + millis;
        return filename;
    }

功能用途:

fileJPG = generateUniqueFileName();

快乐编码!!!

答案 3 :(得分:-1)

您需要为图片使用不同的名称,例如

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
String timeStamp = dateFormat.format(new Date());
String imageFileName = "picture_" + timeStamp + ".jpg";