在 SD 卡中保存新图像而不是覆盖
Saving new image in SD Card instead of overwriting
我创建了一个 android 应用程序,我在其中在屏幕上绘图并通过单击按钮将其保存在图片文件夹中。
代码:
主要活动 :
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;
}
}
现在的问题是,每当我创建新的 canvas 并将其保存在 SD 卡中而不是创建具有唯一名称的新图片时,它 会覆盖之前保存的图片。
我应该怎么做才能在我的文件夹中添加具有唯一名称的新图像保存?
对于每张新图像,您都必须使用新名称保存图像。
例如: 附加时间戳,如:
final File file = new File(path, fileJPG + timestamp+".jpg");
您需要为图片使用不同的名称,例如
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
String timeStamp = dateFormat.format(new Date());
String imageFileName = "picture_" + timeStamp + ".jpg";
或以下代码将为您正在创建的文件创建唯一的随机名称:
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();
编码愉快!!!
只需更改这行代码:
final File file = new File(path, fileJPG + ".jpg");
对此:
final File file = new File(path, fileJPG + "_" + System.currentTimeMillis() + ".jpg");
我创建了一个 android 应用程序,我在其中在屏幕上绘图并通过单击按钮将其保存在图片文件夹中。
代码:
主要活动 :
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;
}
}
现在的问题是,每当我创建新的 canvas 并将其保存在 SD 卡中而不是创建具有唯一名称的新图片时,它 会覆盖之前保存的图片。
我应该怎么做才能在我的文件夹中添加具有唯一名称的新图像保存?
对于每张新图像,您都必须使用新名称保存图像。
例如: 附加时间戳,如:
final File file = new File(path, fileJPG + timestamp+".jpg");
您需要为图片使用不同的名称,例如
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
String timeStamp = dateFormat.format(new Date());
String imageFileName = "picture_" + timeStamp + ".jpg";
或以下代码将为您正在创建的文件创建唯一的随机名称:
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();
编码愉快!!!
只需更改这行代码:
final File file = new File(path, fileJPG + ".jpg");
对此:
final File file = new File(path, fileJPG + "_" + System.currentTimeMillis() + ".jpg");