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_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();
}
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.
Related
This question already has answers here:
Android - Save images in an specific folder
(5 answers)
Closed 6 years ago.
i want to capture an image and save it into specific folder rather than in DCIM/Camera or Gallery...
want to save like: storage/sdcard0/DCIM/MyFolder.
Try this one it may be help you
public void takePicture(){
Intent imgIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "ImagesApp");
imagesFolder.mkdirs(); // <----
File image = new File(imagesFolder, "temp.jpg");
Uri uriSavedImage = Uri.fromFile(image);
imgIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imgIntent,IMAGE_CAPTURE_REQUEST_CODE);
}
You can use the following code
private String save(Bitmap bitmap)
{
File save_path = null;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
try
{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/DirName");
dir.mkdirs();
File file = new File(dir, "DirName_"+new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime())+ ".png");
save_path = file;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100,baos);
FileOutputStream f = null;
f = new FileOutputStream(file);
MediaScannerConnection.scanFile(this, new String[]{file.getAbsolutePath()}, null, null);
if (f != null)
{
f.write(baos.toByteArray());
f.flush();
f.close();
}
}
catch (Exception e)
{
// TODO: handle exception
}
}
return String.valueOf(save_path);
}
Hope this will help you out...
Try following code
private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/DirName/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/DirName/"), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I know the insert method
MediaStore.Images.Media.insertImage(..............)
Insert a thumbnail instaed of the original Bitmap image,I need a way to save Bitmap with no compress to keep its pixels as they are (steganography), I need the image to be stored on gallery in internal storage.
The Gallery can contains folders for application on android, to get high resolution file there is need to store them outside the gallery and tell gallery about your file and your application folder and show your files as thumbnails,so I implement this method which perform what I need and I hope help others
private void SaveImage(Bitmap segg) {
OutputStream fOut = null;
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fileName = "Image-"+ n +".png";
final String appDirectoryName = "TBStego";
final File imageRoot = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), appDirectoryName);
imageRoot.mkdirs();
final File file = new File(imageRoot, fileName);
try {
fOut = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
segg.compress(Bitmap.CompressFormat.PNG, 100, fOut);
try {
Toast.makeText(ExtractActivity.this,
file.getAbsolutePath(),
Toast.LENGTH_LONG).show();
fOut.flush();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE,"stego");
values.put(MediaStore.Images.Media.DESCRIPTION, "stego description");
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.ImageColumns.BUCKET_ID, file.toString().toLowerCase(Locale.US).hashCode());
values.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, file.getName().toLowerCase(Locale.US));
values.put("_data", file.getAbsolutePath());
Toast.makeText(ExtractActivity.this,
file.getAbsolutePath(),
Toast.LENGTH_LONG).show();
ContentResolver cr = getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Toast.makeText(ExtractActivity.this, "The Image thumbnail created in Gallery ", Toast.LENGTH_LONG).show();
}
I have an app where the user creates an image and then I want to save it so it's visible form the default gallery application.
Now I don't want the pictures to be saved in the same folder as the pictures taken from the camera, I want them to be saved in a folder dedicated to the app, just like images from apps like whatsapp or facebook.
I've tried saving them in this two locations:
File imagePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+ File.separator + appDirectoryName + File.separator);
and here
File imagePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+ File.separator + appDirectoryName + File.separator);
If I browse through the phone I see that I successfully save the images but they don't show in the gallery app. It is obvious that I'm missing something but I don't know what it is. Maybe adding some kind of metadata to the files or folders so the gallery recognizes them?
Well I found the answer in the end.
It turned out to be what I suspected. The saved image needs to have some metadata added in order to be seen in the gallery (at least in my device).
This is what I did:
OutputStream fOut = null;
File file = new File(imagePath,"GE_"+ System.currentTimeMillis() +".jpg");
try {
fOut = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
try {
fOut.flush();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, this.getString(R.string.picture_title));
values.put(Images.Media.DESCRIPTION, this.getString(R.string.picture_description));
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis ());
values.put(Images.ImageColumns.BUCKET_ID, file.toString().toLowerCase(Locale.US).hashCode());
values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, file.getName().toLowerCase(Locale.US));
values.put("_data", file.getAbsolutePath());
ContentResolver cr = getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
I have had the same problem.
The second way is the correct way, but you don't see the images in the Gallery because the gallery needs to be refreshed.
So, you can wait a while until it refreshes itself, or you can use the MediaScanner -
look here
Hope this helped!
I did the following to get it to work:
public void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
String mCurrentPhotoPath = "file:" + image.getAbsolutePath(); // image is the created file image
File file = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
Try this
private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/DirName/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/DirName/"), fileName);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I tried this it works perfectly.
private Uri imageUri;
String getimgname, getimgpath;
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "IMG"+System.currentTimeMillis()+".jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
getimgname = photo.getName();
getimgpath = photo.getAbsolutePath();
Try this
MediaScannerConnection.scanFile(context,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
I am working on a drawing part, and have written the following code to save the image to the designated camera folder. However, I would rather like to create a new folder using the app name and save the image to the folder. How could that be made?
I would also like to later on retrieve the image files from that specific folder too.
Thanks!
Current code:
String fileName = "ABC";
// create a ContentValues and configure new image's data
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, fileName);
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpg");
// get a Uri for the location to save the file
Uri uri = getContext().getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
try
{
OutputStream outStream = getContext().getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush(); // empty the buffer
outStream.close(); // close the stream
Try this it might help you.
public void saveImageToExternalStorage(Bitmap image) {
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/directoryName";
try
{
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
File file = new File(fullPath, "image.png");
if(file.exists())
file.delete();
file.createNewFile();
fOut = new FileOutputStream(file);
// 100 means no compression, the lower you go, the stronger the compression
image.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
}
catch (Exception e)
{
Log.e("saveToExternalStorage()", e.getMessage());
}
}
This Method works after so many try.
private String getFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,AUDIO_RECORDER_FOLDER);
if(!file.exists()){
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".mp3");
}
I have a Bitmap image which I have to store in a folder in the SD Card, my code is shown below. It creates the folder and file as expected, but the image is not stored into the file, it remains an empty file... Can anyone tell me what's wrong?
Bitmap merged = Bitmap.createBitmap(mDragLayer.getChildAt(0).getWidth(), mDragLayer.getChildAt(0).getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(merged);
// save to folder in sd card
try {
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "folder");
if(!imagesFolder.exists())
imagesFolder.mkdirs();
int imageNum;
if(imagesFolder.list()==null)
imageNum = 1;
else
imageNum = imagesFolder.list().length + 1;
String fileName = "file_" + String.valueOf(imageNum) + ".jpg";
File output = new File(imagesFolder, fileName);
while(output.exists()){
imageNum++;
fileName = "file_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}
OutputStream fOut = new FileOutputStream(output);
merged.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
First add permission to AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Then write down in Java File as below.
String extr = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extr + "/MyApp");
if (!mFolder.exists()) {
mFolder.mkdir();
}
String strF = mFolder.getAbsolutePath();
File mSubFolder = new File(strF + "/MyApp-SubFolder");
if (!mSubFolder.exists()) {
mSubFolder.mkdir();
}
String s = "myfile.png";
f = new File(mSubFolder.getAbsolutePath(),s);
UPDATED
String strMyImagePath = f.getAbsolutePath();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG,70, fos);
fos.flush();
fos.close();
// MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Don't make it difficult with complex code its really very simple please Try below code.
Create first dir in your sd card :
public static String strpath = android.os.Environment.getExternalStorageDirectory().toString();
public static String dirName = "DIR_NAME";
File makeDirectory = new File(strpath+"/"+dirName);
makeDirectory.mkdir();
Then you should make two String Var like below :
String filename = "yourImageName".jpg";
String dirpath =strpath + "/"+dirName + "/";
Make File Variable :
File storagePath = new File(dirpath);
File myImage = new File(storagePath, filename);
outStream = new FileOutputStream(myImage);
outStream.write(data);
outStream.close();
Hope this may helpful to you.
you just need a bitmap
and you have to pass a path to store the image
Bitmap b = pagesView.getDrawingCache();
b.compress(CompressFormat.JPEG, 100, new FileOutputStream(Environment.getExternalStorageDirectory() + "/NameOfFile.jpg"));
and you have to add permission in Manifest file..
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />