android - add images from drawable folder into a created file directory - android

I'm looking to be able to take png images (called 1.png, 2.png, 3.png) that I have stored in my apps drawable folder and copy/save them to a file directory that is created by my app on launch.I've tried .createnewfile() but was unable to get anything to work.code for creating my file directory below:
//-----create file directory for images
public void createDirectory() {
try {
File imageDirectory = new File(Environment.getExternalStorageDirectory() + "/DCIM/C2AT_IMAGES");
if (!imageDirectory.exists()) {
imageDirectory.mkdirs();
//something here to take images from drawable folder and place them into my newely created directory
File imageFile = new File(Environment.getExternalStorageDirectory() + "/DCIM/C2AT_IMAGES", //something here getDrawable maybe?
);
imageFile.createNewFile();
}
}
catch (Exception e) {
Log.d("MAKE_DIR", "error creating directory");
}
}
thanks

Solved, this is how I done it:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.maptile_1);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory() + "/DCIM/C2AT_IMAGES"
+ File.separator + "test.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
e.printStackTrace();
toastMsg = e.toString();
toast();
}

Related

how to save multiple bitmaps fastly in android studio

I want to save bitmaps in the gallery.
Currently, I am using the following code:
public void saveBitmap(Bitmap output){
String filepath = Environment.getExternalStorageDirectory().toString() + "/Imverter/ImverterEffectedImage";
File dir = new File(filepath);
if(!dir.exists()){
dir.mkdir();
}
String fileName = "Imverter" + System.currentTimeMillis() + ".jpg";
File image = new File(dir, fileName);
try {
FileOutputStream fileOutputStream = new FileOutputStream(image);
output.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
It saves one single bitmap efficiently, but in my app, I have to deal with multiple bitmaps, and this method results in the slow output.
I want to store every single bitmap in a different files.
Thanks in advance.

How to create files to a specific folder in android application?

In my application, I want to create a text file in the cache folder and first what I do is create a folder in the cache directory.
File myDir = new File(getCacheDir(), "MySecretFolder");
myDir.mkdir();
Then I want to create a text file in that created folder using the following code that doesn't seem to make it there. Instead, the code below creates the text file in the "files" folder that is in the same directory as the "cache" folder.
FileOutputStream fOut = null;
try {
fOut = openFileOutput("secret.txt",MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String str = "data";
try {
fOut.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
SO my question is, how do I properly designate the "MySecretFolder" to make the text file in?
I have tried the following:
"/data/data/com.example.myandroid.cuecards/cache/MySecretFolder", but it crashes my entire app if I try that. How should I properly save the text file in the cache/MySecretFolder?
use getCacheDir(). It returns the absolute path to the application-specific cache directory on the filesystem. Then you can create your directory
File myDir = new File(getCacheDir(), "folder");
myDir.mkdir();
Please try this maybe helps you.
Ok, If you want to create the TextFile in Specific Folder then You can try to below code.
try {
String rootPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/MyFolder/";
File root = new File(rootPath);
if (!root.exists()) {
root.mkdirs();
}
File f = new File(rootPath + "mttext.txt");
if (f.exists()) {
f.delete();
}
f.createNewFile();
FileOutputStream out = new FileOutputStream(f);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Just change
fOut = openFileOutput("secret.txt",MODE_PRIVATE);
to
fOut = openFileOutput(myDir+"/secret.txt",MODE_PRIVATE);
This will make secret.txt under MySecretFolder
getPrivateDir will create a folder in your private area (Context.MODE_WORLD_WRITEABLE- use what suits you from Context.MODE_...)
public File getPrivateDir(String name)
{
return context.getDir(name, Context.MODE_WORLD_WRITEABLE);
}
openPrivateFileInput will create a file if it doesn't exist in your private folder in files directory and return a FileInputStream :
/data/data/your.packagename/files
Your application private folder is in
/data/data/your.packagename
public FileInputStream openPrivateFileInput(String name) throws FileNotFoundException
{
return context.openFileInput(name);
}
If you package name is uno.due.com your app private folder is:
/data/data/uno.due.com
All directories underneath are weather created by you or by android for you. When you create a file as above it will go under:
/data/data/uno.due.com/files
Simple and easy code to create folder, file and write/append into the file
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/newfoldername/"; // it will return root directory of internal storage
File root = new File(path);
if (!root.exists()) {
root.mkdirs(); // create folder if not exist
}
File file = new File(rootPath + "log.txt");
if (!file.exists()) {
file.createNewFile(); // create file if not exist
}
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.append("hi this will write in to file");
buf.newLine(); // pointer will be nextline
buf.close();
}
catch (Exception e) {
e.printStackTrace();
}
NOTE: It needs the Android External Storage Permission so add below line in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

How to create a raw image file with content inside to emulate an SD card for Android

I'm working on app which will read folders and files from an SD card, now to need to create a raw image file which will emulate the SD card, but when I use mksdcard it only creates an empty raew image file.
void saveImage() {
File filename;
try {
String path = Environment.getExternalStorageDirectory().toString();
new File(path + "/folder/subfolder").mkdirs();
filename = new File(path + "/folder/subfolder/image.jpg");
FileOutputStream out = new FileOutputStream(filename);
bitMapImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), filename.getAbsolutePath(), filename.getName(), filename.getName());
Toast.makeText(getApplicationContext(), "File is Saved in " + filename, 1000).show();
} catch (Exception e) {
e.printStackTrace();
}
}

How does appear saved SD card images in Android's Gallery?

I save an image to the sdcard and it doesn't appear in the Phone's Gallery. I can see saved image in a folder, but it folder doesn't apper in gallery.
My codes here, how fix it?
img_icon.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
img_resim.buildDrawingCache();
Bitmap bm = img_resim.getDrawingCache();
OutputStream fOut = null;
Uri outputFileUri;
try {
root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
Toast.makeText(context.getActivity(),
"Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
context.getActivity()
.sendBroadcast(
new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://"
+ Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))));
return true;
}
});
return rowView;
}
Thanks for helping..
Your problem lies here:
context.getActivity()
.sendBroadcast(
new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://"
+ Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))));
You are asking Android to re-index all of the files in Environment.DIRECTORY_PICTURES.
Asking to scan a whole directory tree is wasteful. In your case, it it even more wasteful, since you are not writing your file to that directory. Instead, you are writing that file to:
root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
Hence, your scan will not pick up this file, which you are writing to some random spot on external storage.
You need to decide the proper place to store your file, then index that one file.

Store Bitmap image to SD Card in Android

I am facing some strange problem with my android code,
I have an image in Bitmap variable and want to save that file to SD card.
I code as follow,
Bitmap IMAGE // Loaded from internet servers.;
try {
File _sdCard = Environment.getExternalStorageDirectory();
File _picDir = new File(_sdCard, "MyDirectory");
_picDir.mkdirs();
File _picFile = new File(_picDir, "MyImage.jpg");
FileOutputStream _fos = new FileOutputStream(_picFile);
IMAGE.compress(Bitmap.CompressFormat.JPEG, 100, _fos);
_fos.flush();
_fos.close();
Toast.makeText(this, "Image Downloaded", 7000).show();
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(this, ex.getMessage(), 7000).show();
}
I am using Sony Experia Arc as my testing device, when the phone is connected to my computer, the code works nice, it stores image and also displays in gallery. But when I disconnect phone from my computer and test the app, it doesn't save picture and doesn't show any exception.
use this function
void saveImage() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
String fname = "Image.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Check this answer will give more details Android saving file to external storage
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
**This Code Cover the Following Topics**
1. Save a bitmap Image on sdcard a jpeg
2. Create a folder on sdcard
3. Create every file Separate name
4. Every file save with date and time
5. Resize the image in very small size
6. Best thing image Quality fine not effected from Resizing
The following method is used to create an image file using the bitmap
public void createImageFromBitmap(Bitmap bmp) {
FileOutputStream fileOutputStream = null;
try {
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Capture/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
//Capture is folder name and file name with date and time
fileOutputStream = new FileOutputStream(String.format(
"/sdcard/Capture/%d.jpg",
System.currentTimeMillis()));
// Here we Resize the Image ...
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100,
byteArrayOutputStream); // bm is the bitmap object
byte[] bsResized = byteArrayOutputStream.toByteArray();
fileOutputStream.write(bsResized);
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Categories

Resources