android sd card path for all devices - android

I tried to get sd card path to store image using this code:
String filepath = Environment.getExternalStorageDirectory().getAbsolutePath();
But it didnot work for all devices and all versions of android.

Try this:
String sdcardPath = Environment.getExternalStorageDirectory().getPath();

I succeeded to do it using this code:
public File getSDPath() {
String filepath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
if (android.os.Build.DEVICE.contains("samsung")
|| android.os.Build.MANUFACTURER.contains("samsung")) {
File f = new File(Environment.getExternalStorageDirectory()
.getParent() + "/extSdCard");
if (f.exists() && f.isDirectory()) {
try {
File file = new File(f, "test");
FileOutputStream fos = new FileOutputStream(file);
filepath = Environment.getExternalStorageDirectory()
.getParent() + "/extSdCard";
} catch (FileNotFoundException e) {
}
} else {
f = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/external_sd");
if (f.exists() && f.isDirectory()) {
try {
File file = new File(f, "test");
FileOutputStream fos = new FileOutputStream(file);
filepath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/external_sd";
} catch (FileNotFoundException e) {
}
}
}
}
return new File(filepath);
}

Related

How to save bitmap in custom gallery?

I have understood that I can create a folder in DCIM and if there is a file in it, the dir is displayed as an album name. I can create the dir just fine, in this case, I call the dir "ThoughtCast."
I try saving a PNG file, however, and it does not appear.
Here is my code:
public void savebitmap(Bitmap bmp) throws IOException {
String file_path =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "ThoughtCast/";
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "sketchpad" + ".png");
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
}
Any help will be appreciated. Thanks
Try this it may help you (it's in kotlin)
I am currently do this task
private fun saveImage(bitmap: Bitmap) {
var outStream: FileOutputStream? = null
// Write to SD Card
try {
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "ThoughtCast/")
dir.mkdirs()
val fileName = String.format("%s_%d.jpg", "Image", System.currentTimeMillis())
val outFile = File(dir, fileName)
outStream = FileOutputStream(outFile)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream)
outStream.flush()
outStream.close()
Utils.showSnackBar(binding.rootView, getString(R.string.image_saved))
} catch (e: FileNotFoundException) {
Crashlytics.logException(e)
} catch (e: IOException) {
Crashlytics.logException(e)
} finally {
}
}
Try This Code Below. It may work for You.
private void saveImageStorage(Bitmap finalBitmap) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DICM).toString();
File myDir = new File(root + "/" + <your folder if you want>);
if(!myDir.exists()){
myDir.mkdir();
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
// inform to the media scanner about the new file so that it is immediately available to the user.
MediaScannerConnection.scanFile(this, 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);
}
});
}

Trying to create folder in internal storage but code working only in oppo handset not in other brand handsets

Trying to create folder in internal storage but code working only in oppo handset not in other brand handsets like samsung,mi etc
public void createPDF()
{
TextView dttt = (TextView)findViewById(R.id.dttt);
String da = dttt.getText().toString();
final Cursor cursor = db.getDateWise(da);
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/CollactionApp"+ "/PDF";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
Log.d("PDFCreator", "PDF Path: " + path);
int i = 1;
File file = new File(dir, "Datewise" + da + ".pdf" );
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
}
// Check premissions in Manifest and at run time
String root_sd = Environment.getExternalStorageDirectory().toString();
createExDirectory("CollactionApp", root_sd);
String path = root_sd + "/CollactionApp"+ "/PDF.pdf";
File f = new File(path);
try {
if (!f.exists()) {
f.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
public static String createExDirectory(String folderName, String pathToExternalStorage) {
String returnPath = "";
boolean success = false;
Boolean isSDPresent = Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED);
if (isSDPresent) {
// SD-card is present
File appDirectory = new File(pathToExternalStorage + "/" + folderName);
if (appDirectory.exists()) {
success = true;
} else {
success = appDirectory.mkdirs();
}
if (success) {
returnPath = appDirectory.getAbsolutePath();
} else {
}
}
return returnPath;
}
The path you are using points to the external storage. I've had an app before which have been working for long on all devices until recently, so I had to do a refactor on it, so I don't use the getExternalStorageDirectory() anymore.
I now use the Context's getFilesDir(), on which I didn't get the same issue again.
You would want your path to be something like below to use internal storage.
File internalDir = getContext().getFilesDir();
File myFolder = new File(internalDir, "/CollactionApp"+ "/PDF");
String path = myFolder.getAbsolutePath;

Save Images to specific Folder in Phone Android [duplicate]

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();
}
}

Sharing image failed

I'm trying to share an image but I don't know why I'm failing, could you help me please?
String imageUrl = web.get(position).getImage();
if (!imageUrl.startsWith("http://") && !imageUrl.startsWith("https://"))
imageUrl = "http://" + imageUrl;
Button button = (Button)rowView.findViewById(R.id.condividi);
final String finalImageUrl = imageUrl;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_TEXT, web.get(position).getTitle());
File file = writebitmaptofilefirst("the image", finalImageUrl );
Uri path = Uri.fromFile(file);
intent.putExtra(Intent.EXTRA_STREAM, path );
Intent send = Intent.createChooser(intent, null);
context.startActivity(send);
}
});
public static File writebitmaptofilefirst(String filename, String source) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extStorageDirectory + "/temp_images");
if (!mFolder.exists()) {
mFolder.mkdir();
}
OutputStream outStream = null;
File file = new File(mFolder.getAbsolutePath(), filename + ".jpg");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, filename + ".jpg");
Log.e("file exist", "" + file + ",Bitmap= " + filename);
}
try {
URL url = new URL(source);
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("file", "" + file);
return file;
}
EDIT
String imageUrl = web.get(position).getImage();
if (!imageUrl.startsWith("http://") && !imageUrl.startsWith("https://"))
imageUrl = "http://" + imageUrl;
Button button = (Button)rowView.findViewById(R.id.condividi);
final String finalImageUrl = imageUrl;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_TEXT, web.get(position).getTitle());
String file = writebitmaptofilefirst("ndp_image", finalImageUrl);
//Uri path = Uri.fromFile(file);
intent.putExtra(Intent.EXTRA_STREAM, file );
Intent send = Intent.createChooser(intent, null);
context.startActivity(send);
}
});
return rowView;
}
public static String writebitmaptofilefirst(String filename, String source) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extStorageDirectory + "/temp_images/");
if (!mFolder.exists()) {
mFolder.mkdir();
}
OutputStream outStream = null;
File file = new File(mFolder.getAbsolutePath(), filename + ".jpg");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, filename + ".jpg");
Log.e("file exist", "" + file + ",Bitmap= " + filename);
}
try {
URL url = new URL(source);
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("file", "" + file);
return file.getAbsolutePath();
}
Add permissions to your manifest
Remove space from file name (the image). With space you need decode the uri. You should paass the full path return file.getAbsolutePath(). You are just passing the file name.
In the case of file exists your not storing in the same path. You were not included the dictionary. extranlstoragepath+/temp_images/+the image.jpg try to log your file paths. And
File file = new File(mFolder.getAbsolutePath(), filename + ".jpg");
You have missed a / between two paramaters.
Wonderful blogpost about storing image

Save Bitmap to SD Card

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" />

Categories

Resources