Android - set file name while saving image using Bitmap.compress
I'm saving an image onto sd card using the following code:
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_UR开发者_运维百科I, 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();
}
But the image file name is always the System.currentTimeMills. How do I specify a name for it?
Here's my complete working code based on dipu's suggestion:
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);
}
Try the following approach.
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);
//now write your bytes into this outputstream.
精彩评论