How to store bitmap image in file in sdcard? - android

bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
cacheFile = new File(android.os.Environment.getExternalStorageDirectory(), "Android/data/"+this.getPackageName()+"/cache/");
if(!cacheFile.exists())
{
cacheFile.mkdir();
}
try {
fileOutputStream = new FileOutputStream(cacheFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
Log.i("Error", e.getMessage());
}
}
but I am getting error that mnt/sdcard/Android/data/com.android.linegame/cache file not exist

Which versoin of Android you are using?? Because Android 2.2 contains folder "Android" in mnt/sdcard. But Android 4.0 version doesn't contain folder "Android".
Add following code:
cacheFile = new File(Environment.getExternalStorageDirectory(), "/Android/data/"+this.getPackageName()+"/cache/");
if(!cacheFile.exists()) {
cacheFile.mkdirs();
}

Related

android files io where should i put source file

i want to store a picture ,but i dont know where should i put "b.jpg" in android studio,it should be in "Drawable" or the others
PS:"b.jpg"is PC file
here is my code
String externalDir = Environment.getExternalStorageDirectory().toString();
imgFile = externalDir + "/b.jpg";
iv_file = findViewById(R.id.image);
iv_file.setDrawingCacheEnabled(true);
Button btn_img_save = findViewById(R.id.btn_img_save);
Button btn_img_open = findViewById(R.id.btn_image_read);
btn_img_save.setOnClickListener(this);
btn_img_open.setOnClickListener(this);
}
private void saveBitmap(String path, Bitmap bitmap) {
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(path));
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
}

How to create Image File inside Internal Cache Directory in Android

I want to have image.png inside cache/images/ in Internal Storage of Android.
I am not able to have it with following code:
File directory = new File(getContext().getCacheDir(), "images");
directory.mkdirs();
File mypath=new File(directory,"image.png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
With the above code I am not even able to create a directory named images. Pls help, I am beginner.
Try this:
File sd = getCacheDir();
File folder = new File(sd, "/myfolder/");
if (!folder.exists()) {
if (!folder.mkdir()) {
Log.e("ERROR", "Cannot create a directory!");
} else {
folder.mkdirs();
}
}
File fileName = new File(folder,"mypic.jpg");
try {
FileOutputStream outputStream = new FileOutputStream(String.valueOf(fileName));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I have implemented it like this...
//create file
File file = new File(context.getExternalCacheDir(), System.currentTimeMillis() + ".png");
//draw image if created successfully
if (file.createNewFile()) {
//initialize image BitMap
Bitmap bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
//initialize canvas and paint object
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
//design part goes here using Paint and Canvas
...
//get file output stream and draw design on image file
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}

Dynamically created image file cannot be found in Gallery or image picker in Android

I am developing an Android app. In my app, I am creating image file from bitmap then save it to device. The process of creating image file from bitmap and save image to device is okay. The problem is I cannot find that created image in gallery. But the file really exist when I search it from file manager.
Here is my code:
File file = null;
try{
String fileName = String.valueOf(System.currentTimeMillis())+".jpeg";
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName);
if(file.exists()){
file.delete();
}
OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
template.getBitmap().compress(Bitmap.CompressFormat.JPEG, 100, os);
os.close();
Toast.makeText(context,"Templated saved to your device",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(context,e.getMessage(),Toast.LENGTH_SHORT).show();
}
As you can see, I save it in the picture folder. I tried save it in download folder as well. File saved to device successfully but the problem is image is not displayed in Gallery. But exist in file manager. How can I make that image searchable in gallery?
try this:
File file = null;
try{
String fileName = String.valueOf(System.currentTimeMillis())+".jpeg";
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName);
if(file.exists())
{
file.delete();
}
OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
template.getBitmap().compress(Bitmap.CompressFormat.JPEG, 100, os);
os.close();
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
Toast.makeText(context,"Templated saved to your device",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(context,e.getMessage(),Toast.LENGTH_SHORT).show();
}
Use this code after saving file
try {
MediaScannerConnection.scanFile(context,
new String[] { mPath }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
}

write image in external directory android

How to write image in phone directory. Directory is created but i could not write image in this folder. Here is my code .please check if i am doing something wrong thanks in advance.
Bitmap bitmap;
String directory = new_path; // I am getting path here of image like sdcard/0/emulated/image.jpg
String folder_name = "abc"
bitmap = BitmapFactory.decodeFile(directory);
iv_6.setImageBitmap(bitmap); // image displayed here but not saving in directory.
try {
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator +folder_name);
f.mkdirs();
FileOutputStream fo = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, fo);
fo.close();
}catch (Exception e)
{
e.printStackTrace();
}
public void savePng(Bitmap bitmap, String filePath) {
try {
File temp = new File(filePath);
FileOutputStream os = new FileOutputStream(temp + ".png");
bitmap.compress(Bitmap.CompressFormat.PNG, 50, os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}

write an image to external storage in android

I use following code to write an image to external storage in android :
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
fileName = "image_2.jpeg";
File file = new File(dir, fileName);
try {
FileOutputStream outStream = new FileOutputStream(file);
Bitmap bitmap = BitmapFactory.decodeFile("android.resource://com.mypackage.com/drawable/image_1");
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This code is for reading image_1.jpg from drawable folder, then writing it to download folder in external storage, with image_2.jpeg name. (create download folder in external storage and a file with image_2.jpeg name inside that folder).
This code will produce an ((force close)). download folder is created and also the image_2.jpeg is created, but image image_2.jpeg is corrupted.
These images in drawable folder can be accessed by BitmapFactory, you can save the bitmap to PNG or JPG.
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
File sd = Environment.getExternalStorageDirectory();
String fileName = "test.png";
File dest = new File(sd, fileName);
try {
FileOutputStream out;
out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Don't forget to add android.permission.WRITE_EXTERNAL_STORAGE permission.
For other type of images, I think put them into assets folder is a better way.
There is a sample here.
I did same thing with this code.Try this code:
String[] sampleImagesName = { "image2" };
int[] sampleImages = { R.drawable.image1};
File file;
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/download");
if (!file.exists()) {
file.mkdirs();
SaveSampleToSD();
}
}
private void SaveSampleToSD() {
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/download";
for (int i = 0; i < sampleImages.length; i++) {
try {
File f = new File(path + "/", sampleImagesName[i] + ".jpg");
Bitmap bm = BitmapFactory.decodeResource(getResources(),
sampleImages[i]);
FileOutputStream out = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
Log.e("ImageSaved---------", "saved");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Categories

Resources