I am working on an app in which I would like to save some Bitmaps to the SD Card. I have looked at a lot of examples and other questions, and from that I have made the following code:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String dirPath = Environment.getExternalStorageDirectory().toString() + "/myFolder";
File dir = new File(dirPath);
dir.mkdirs();
String fileName = "bitmapname.jpg";
File file = new File(dirPath, fileName);
FileOutputStream fileOutPutStream;
try {
boolean created = file.createNewFile();
Log.d("Checks", "File created: " + created);
fileOutPutStream = new FileOutputStream(file);
fileOutPutStream.write(byteArrayOutputStream.toByteArray());
fileOutPutStream.close();
} catch (FileNotFoundException e) {
Log.d("Checks", "FileNotFoundException");
e.printStackTrace();
} catch (IOException e) {
Log.d("Checks", "IOException");
Log.d("Checks", e.getMessage());
e.printStackTrace();
}
I don't see what's wrong with this code. It doesn't give any errors and my app runs without crashing. However, when I connect my phone to my computer and open the SD Card I do not see the folder "myFolder" and I can not find the saved image anywhere. Do you guys have any ideas as to why this is?
EDIT: I noticed that I can see the saved bitmaps in the Android gallery, and they are indeed in a folder called "myFolder". However, I still don't see them when I connect my phone to my computer and browse my sd card.
From my experience I had similar issued when I forgot the fileOutPutStream.flush(); before the close().
Are you sure you are setting the permission to write to SD card? Try setting this one:
WRITE_EXTERNAL_STORAGE
Edit:
Ok, try this:
Environment.getExternalStorageDirectory().getAbsolutePath()
Instead of:
Environment.getExternalStorageDirectory().toString()
Or even create a directory like this:
File dir = new File(Environment.getExternalStorageDirectory() +
File.separator +
"myFolder");
dir.mkdirs();
Related
I'm trying to write a text file in android's internal storage and browse through connecting it to a PC via usb. Now, I used the following code which worked fine for old devices with SD cards.
public void writeToFile(String stringToBeWritten)
{
final File path =
Environment.getExternalStoragePublicDirectory
(
Environment.DIRECTORY_DCIM + "/Target Folder/"
);
if(!path.exists())
{
path.mkdirs();
}
final File file = new File(path, "MyFile.txt");
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(stringToBeWritten);
System.out.println("Written Successfully");
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
I've been surfing for a solution a while and tried a lot of thing to get my job done. All the solutions out there, to store the file internally but unable to browse.
Any ideas how to write my files on internal phone storage? I'd highly appreciate any help/suggestions. Thanks.
I am trying to save a bitmap that is created by the user to the default 'Pictures' folder on the device. I will start with the option that seems to be the more common method:
public void saveImageToExternalStorage(String filename, Bitmap image) {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
try {
File directory = new File(path);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory, filename + ".jpeg");
file.createNewFile();
OutputStream outputStream = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
This is supposed to save to the 'Pictures' folder, but Environment.getExternalStorageDirectory().getAbsolutePath() seems to create a new file structure like this file://storage/emulated/11/Pictures/ and save the picture to that. I have also tried Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) with the same result. But this is not the default 'Pictures' folder on any of my test devices or emulators. Which led me to look for other methods, and I found this:
public void saveImageToExternalStorage(String filename, Bitmap image) {
try {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, filename);
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri filepath = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
OutputStream outputStream = getContentResolver().openOutputStream(filepath);
image.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
This actually saves to the default file structure, which apparently looks like this: content://media/external/images/media/4282. But there seems to be no way to specify the filename of the image (Media.TITLE just sets the title attribute, not the actual filename), it saves as a (seemingly) random string of numbers. I looked at the API Guide for MediaStore.Images.Media and there does not seem to be any other variable that would set the filename. This also does not seem to be the correct way of saving, according to the Android Developer Guides. I would like to know if there is any way of saving to this folder, while also setting my own filename. And if this method could produce unforeseen problems on other devices.
EDIT:
For anyone interested this is my current code, based on the answer by #CommonsWare:
public void saveImageToExternalStorage(Context context, String filename, Bitmap image) throws IOException {
File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(directory, filename + ".jpeg");
FileOutputStream outputStream = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.getFD().sync();
outputStream.close();
MediaScannerConnection.scanFile(context, new String[] {file.getAbsolutePath()}, null, null);
}
This is supposed to save to the 'Pictures' folder
getExternalStorageDirectory() returns the root of external storage, not some location inside of it (e.g., Pictures/, DCIM/, Movies/).
I have also tried Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) with the same result
That will give you the proper directory, or whatever the device thinks the proper directory is (usually named Pictures/ in external storage for whoever the current user is).
but Environment.getExternalStorageDirectory().getAbsolutePath() seems to create a new file structure like this file://storage/emulated/11/Pictures/
The 11 is a bit unusual, and getAbsolutePath() does not return something with a file:// scheme, but otherwise that seems about right.
But this is not the default 'Pictures' folder on any of my test devices or emulators.
I do not know how you have determined this.
I would like to know if there is any way of saving to this folder, while also setting my own filename.
Start with your first sample, switching to DIRECTORY_PICTURES. Then:
have outputStream be a FileOutputStream
call outputStream.getFD().sync() after flush() and before close()
use MediaScannerConnection and its scanFile() method to arrange for the MediaStore to index the image, so it is available to on-device galleries, desktop OS file managers, etc.
With Android 6.0 Marshmallow (API >= 23), Google introduced a new permission model.
You have to request permission at run-time:
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, WRITE_REQUEST_CODE);
and handle the result in onRequestPermissionsResult(),
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "db.JPG");
try {
file.createNewFile();
}
catch (IOException e) {
Toast.makeText(this.getApplicationContext(),
"createNewFile:"+e.toString(),
Toast.LENGTH_LONG).show();
}
then
if (Build.VERSION.SDK_INT < 19) {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + filename)));
}
else {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://" + filename)));
}
to show in the gallery.
I'm having a problem. I'm trying to create a bitmap in a directory on my phone. However it doesn't always work and never seems to work right away. After running if I look in the directory it wont be there, I have to fiddle around in other folders and keep refreshing before it shows up, often it doesn't even show up at all. I do not understand this, any help or insight would be very much appreciated, thanks
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myImage.compress(Bitmap.CompressFormat.PNG, 40, bytes);
try {
File f = new File(Environment.getExternalStorageDirectory() + "/myDirectory/" + "test.png");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
Log.e(TAG, "Was unable to copy image" + e.toString());
}
If for some reason someone comes across this with a similar problem, I found out the solution. For whatever reason the file wont show up until I disconnect the phone from the USB cable. The second I do the files show up.
You are trying to create the file without having created the /myDirectory/ folder first, so it may fail to create your file. Also, you must check the return value of f.createNewFile(), because it will return false if the file already exists. For really checking if the file exists, use f.exists() instead.
So, if you change your code to:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
Log.i("COMPRESSED Bitmap", " "+myImage.compress(Bitmap.CompressFormat.PNG, 40, bytes));
try {
File directory = new File(Environment.getExternalStorageDirectory() + "/myDirectory/");
Log.i("Created external folder successfully", " "+directory.mkdirs());
File f = new File(Environment.getExternalStorageDirectory() + "/myDirectory/" + "test.png");
Log.i("Created external file successfully", " "+f.createNewFile() + " file exists "+ f.exists());
if(f.exists()){
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
}
} catch (IOException e) {
e.printStackTrace();
Log.e("MyActivity", "Was unable to copy image" + e.toString());
}
It will only write to the file if it already exists. I tested it and the file is always there, and is replaced by another if you execute the code a second or third time.
I'm a newbie Android developer. I have loaded an image using universal-image-loader and I would like to save it on my sd card. The file is created in the desired directory with the correct filename, but it always has a size of 0. What am I doing wrong?
A relevant snippet follows:
PS: The image already exists on disk, it's not being downloaded from the Internet.
private void saveImage(String imageUrls2, String de) {
String filepath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
File SDCardRoot = Environment.getExternalStorageDirectory()
.getAbsoluteFile();
String filename = de;
File myDir = new File(SDCardRoot+"/testdir");
Bitmap mSaveBit = imageLoader.getMemoryCache();
File imageFile = null;
try {
//create our directory if it does'nt exist
if (!myDir.exists())
myDir.mkdirs();
File file = new File(myDir, filename);
if (file.exists())
file.delete();
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bos.flush();
bos.close();
} catch (IOException e) {
filepath = null;
e.printStackTrace();
Toast.makeText(getApplicationContext(),
R.string.diskful_error_message, Toast.LENGTH_LONG)
.show();
}
Log.i("filepath:", " " + filepath);
}
Yes, your code creates an file on sdcard_root/testdir/de only, and didn't write anything to it. Is "imageUrls2" the source image file? If yes, you can open that file with BufferedInputStream, read the data from BufferedInputStream, and copy them to output file with bos.write() before bos.flush() and bos.close().
Hope it helps.
I am trying to write a jpg image to the external SD card. However, I am getting System.err FileNotFoundException: /mnt/sdcard/test.images/temp/savedImage (no such file or directory). Creating the directory also seems to fail and gives a false in LogCat and I also cannot see the folder when looking on my SD card.
My code is as follows:
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File folder = new File(Environment.getExternalStorageDirectory() + "/test.images/temp");
try {
if(!folder.exists()){
boolean dir = new File(Environment.getExternalStorageDirectory() + "/test.images/temp").mkdir();
Log.v("creating directory", Boolean.toString(dir));
}
File imageOutputFile = new File(Environment.getExternalStorageDirectory() + "/test.images/temp", "savedImage");
FileOutputStream fos = new FileOutputStream(imageOutputFile);
Image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I have permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
in the manifest and have cleaned and rebuilt.
Use mkdirs() instead of mkdir().
Guido posted a solution that works for me in the comment. I am going to repeat it just to make sure it can be an answer.