How to save bitmap in custom gallery? - android

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

Related

unable to save image to gallery from ImageView in Android

Facing problem in saving image to gallery from webview.....storage permission is granted but it does not work.... i have tried all that i can do...kindly help me
here is the code below
private void saveImageToExternalStorage(Bitmap finalBitmap) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/ahmed");
myDir.mkdirs();
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, 100, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
// Tell the media scanner about the new file so that it is
MediaScannerConnection.scanFile(getActivity(), 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);
}
});
}
And this is the button onClick()
cvDownload.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
anImage = ((BitmapDrawable) ivPhoto.getDrawable()).getBitmap();
saveImageToExternalStorage(anImage);
Toast.makeText(getContext(), "Download successfuly"+anImage.toString(),
Toast.LENGTH_SHORT).show();
}
});
it is work for me:
public void onCreate(){
File path=saveBitmap(bitmap);
MediaScannerConnection.scanFile(this, new String[]{path.getPath()}, new String[]{"png", "jpg"}, new MediaScannerConnection.OnScanCompletedListener() {
/*
* (non-Javadoc)
* #see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
*/
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
// sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(path)));
startActivity(intent); /** replace with your own uri */
// finish();
// finishAffinity();
}
});
}
public static File saveBitmap(Bitmap bitmap) {
String fileName = "";
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/MyImages");
dir.mkdirs();
fileName = String.format("%d.jpeg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try {
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return outFile;
}
Follow this code to download image from the ImageView:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
try {
val bitmap = imageView.getDrawable().toBitmap()
var outStream: FileOutputStream? = null
val sdCard: File = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
val dir = File(sdCard.getAbsolutePath().toString() + "/sastana")
dir.mkdirs()
val fileName = String.format("%d.jpg", System.currentTimeMillis())
val outFile = File(dir, fileName)
outStream = FileOutputStream(outFile)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream)
outStream.flush()
outStream.close()
Toast.makeText(this, "Saved Successfully", Toast.LENGTH_SHORT).show()
} catch (e : Exception) {
Log.e("qrcode", e.toString())
}
} else {
Log.e("qrcode", "permission not granted")
}

while compressing the image using bitmap (image)saving to the gallery but image failed to load -Android

I am using bitmap.But after capturing image I am trying to save image in External storage it is getting blured.Please give me solution.
This is my code -
public void saveImageToExternalStorage() {
String root =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file1 = new File(myDir, fname);
if (file1.exists())
file1.delete();
try {
FileOutputStream out = new FileOutputStream(file1);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this, new String[] { file1.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
}
you need to notify the gallery that a new image with a path is added or i should say that you must update the MediaStore so that it will be added in Media Store as new Image
private void addImageGallery( File file ) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); // setar isso
getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
It's probably compression fault. Try to modify the parameters of
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
to eg:
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
or save it to lossless PNG format if it's not against your requirements:
finalBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
Source:
https://developer.android.com/reference/android/graphics/Bitmap.html#compress(android.graphics.Bitmap.CompressFormat, int, java.io.OutputStream)

android sd card path for all devices

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

Save Bitmap into File and return File having bitmap image

I have a problem to save Bitmaps into files.
My method is like this:
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
OutputStream outStream = null;
File file = new File(bmp + ".png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, bmp + ".png");
Log.e("file exist", "" + file + ",Bitmap= " + bmp);
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("file", "" + file);
return file;
}
It gives me error of file.I am calling this method like this:
Drawable d = iv.getDrawable();
Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
File file = savebitmap(bitmap);
Please help me...
I try to make some corrections on your code
I assume that you want to use filename instead of bitmap as parameter
private File savebitmap(String filename) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(filename + ".png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, filename + ".png");
Log.e("file exist", "" + file + ",Bitmap= " + filename);
}
try {
// make a new bitmap from your file
Bitmap bitmap = BitmapFactory.decodeFile(file.getName());
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("file", "" + file);
return file;
}
You can't write like this
File file = new File(bmp + ".png");
and this line is also wrong
file = new File(extStorageDirectory, bmp + ".png");
You have to give string value and not bitmap.
File file = new File(filename + ".png");
Change
File file = new File(bmp + ".png");
to
File file = new File(extStorageDirectory,"bmp.png");
like you did nearly the second time.

Saving image overwrite in sdcard android

i'm using the following code for saving the image
FrameLayout mainLayout = (FrameLayout) findViewById(R.id.frame);
// File root = Environment.getExternalStorageDirectory();
// File file = new File(root, "androidlife.jpg");
// File file = new File(Environment.getExternalStorageDirectory()
// + File.separator + "/test.jpg");
Random fCount = new Random();
// for (int i = 0; i < 10; i++) { Comment by Lucifer
int roll = fCount.nextInt(600) + 1;
//System.out.println(roll);
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test" + String.valueOf(roll) +".jpg" );
Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(),
mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
mainLayout.draw(c);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
// } Comment by Lucifer
it save the image perfectly but overwrite when i press the save button twice...What can be the issue? Any sugestion??
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test.jpg");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(),
mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
mainLayout.draw(c);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
You have given a static file name.
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test.jpg");
So, Everytime it is going to create a image with test.jpg name and at a same location. The only logic you need to implement is to change your file name to be a dynamic file name. You can try it in this way
static int fCount = 0;
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test" + String.valueOf(fCount++) +".jpg" );
Now above line is going to create a new file every time, starting with name test0.jpg, test1.jpg ... and so on.
But this could create a problem when you close your application and restart your application. Because it will going to start again from 0 counter.
So i suggest you to go with a random number contacatination with file name.
sticker_view.setLocked(true);
sticker_view.setDrawingCacheEnabled(true);
Bitmap bitmap = sticker_view.getDrawingCache();
Log.e("BITMAP", "onOptionsItemSelected: " + bitmap);
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/Edited Image");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String photoName = "Image-" + n + ".jpg";
Log.e("PHOTONAME", "onOptionsItemSelected: " + photoName);
File file = new File(newDir, photoName);
String filePath = file.getAbsolutePath();
Log.e("FILEPATH", "onOptionsItemSelected: " + filePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(EditActivity.this, "Image Already Exist.", Toast.LENGTH_SHORT).show();
} else {
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileOutputStream out = new FileOutputStream(file);
Log.e("OUT", "onOptionsItemSelected: " + out);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
bitmap.recycle();
Toast.makeText(EditActivity.this, "Saved In Edited Image.", Toast.LENGTH_SHORT).show();
item.setVisible(false);
MediaScannerConnection.scanFile(EditActivity.this, new String[]{file.getAbsolutePath()},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Intent intent = new Intent();
intent.setAction("URI");
intent.putExtra("uri", filePath);
sendBroadcast(intent);
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
You can just add System.currentTimeMillis() in the name of your file name to get a complete unique file name. This will add current time in milliseconds since epoch to your file name and unless you can create more than one file in a single millisecond, no overwrite will be done.

Categories

Resources