我正在使用以下代码将图像保存到SD卡上:
ContentValues values = new ContentValues();
values.put(MediaColumns.TITLE, mFileName);
values.put(MediaColumns.DATE_ADDED, System.currentTimeMillis());
values.put(MediaColumns.MIME_TYPE, "image/jpeg");
resultImageUri = ApplyEffects.this.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
try{
OutputStream out = ApplyEffects.this.getContentResolver().openOutputStream(resultImageUri);
mResultBitmaps[positionSelected].compress(Bitmap.CompressFormat.JPEG, 70, out);
out.flush();
out.close();
} catch(FileNotFoundException e){
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
但是图像文件名始终是System.currentTimeMills。如何为其指定名称?
答案 0 :(得分:1)
这是我基于dipu建议的完整工作代码:
private Uri saveToFileAndUri() throws Exception{
long currentTime = System.currentTimeMillis();
String fileName = "MY_APP_" + currentTime+".jpg";
File extBaseDir = Environment.getExternalStorageDirectory();
File file = new File(extBaseDir.getAbsoluteFile()+"/MY_DIRECTORY");
if(!file.exists()){
if(!file.mkdirs()){
throw new Exception("Could not create directories, "+file.getAbsolutePath());
}
}
String filePath = file.getAbsolutePath()+"/"+fileName;
FileOutputStream out = new FileOutputStream(filePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, out); //control the jpeg quality
out.flush();
out.close();
long size = new File(filePath).length();
ContentValues values = new ContentValues(6);
values.put(Images.Media.TITLE, fileName);
// That filename is what will be handed to Gmail when a user shares a
// photo. Gmail gets the name of the picture attachment from the
// "DISPLAY_NAME" field.
values.put(Images.Media.DISPLAY_NAME, fileName);
values.put(Images.Media.DATE_ADDED, currentTime);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.ORIENTATION, 0);
values.put(Images.Media.DATA, filePath);
values.put(Images.Media.SIZE, size);
return ThisActivity.this.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}
答案 1 :(得分:0)
尝试以下方法。
String fileName = "my_file.jpg";
File extBaseDir = Environment.getExternalStorageDirectory();
File file = new File(extBaseDir.getAbsoluteFile() + "APP_NAME");
if(!file.exists()){
if(!file.mkdirs()){
throw new Exception("Could not create directories, "+file.getAbsolutePath());
}
}
String filePath = file.getAbsolutePath()+"/"+fileName;
FileOutputStream out = new FileOutputStream(filePath);
//现在将您的字节写入此输出流。