i am working on wallpaper app in which i am downloading image, but i am having problem of image replacing.
when ever i download new image it gets replaced with previous one.
this is my code:
public void saveImageToSDCard(Bitmap bitmap) {
String dirname = "/Amazing Wallpapers/";
File myDir = new File(Environment
.getExternalStorageDirectory().getPath() + dirname);
myDir.mkdirs();
String str = currentUrl.substring(
currentUrl.lastIndexOf('/')+1,
currentUrl.length());
String fname = "Wallpaper-" + str + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
Toast.makeText(
_context,
_context.getString(R.string.toast_saved).replace("#",
"\"" + pref.getGalleryName() + "\""),
Toast.LENGTH_SHORT).show();
Log.d(TAG, "Wallpaper saved to:" + file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(_context,
_context.getString(R.string.toast_saved_failed),
Toast.LENGTH_SHORT).show();
}
}
Just use the current Date time in milliseconds as unique identifier to your File. Like this:
String str = String.valueOf(System.currentTimeMillis());
I tested your code and it is working.
Related
I have made an app that uses the filter image and save in sdcard it's working good but I want to save image in two resolution high and low, I have never tried on resolution, Any one one can help that how to save in these both resolution? My code is below
private void saveBitmap(Bitmap bmp, String fileName, int resolution, String resolutionQuality) {
// File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + fileName + ".png");
File f = new File(Environment.getExternalStorageDirectory() + "FiltureImages");
if (!f.exists()) {
File wallpaperDirectory = new File("/sdcard/FiltureImages/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/FiltureImages/"), fileName + resolutionQuality + ".png");
if (file.exists()) {
file.delete();
}
try {
fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, resolution, fos);
Toast.makeText(mActivity, "Image save successfully", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Call like this saveBitmap(bm, "high", "low", 100, 0, "quality");
Quality range from 0 -100
Note: change Bitmap.CompressFormat.PNG to Bitmap.CompressFormat.JPEG beacuse quality works with JPEG format.
private void saveBitmap(Bitmap bmp, String fileNameHigh, String fileNameLow, int resolutionHigh, int resolutionLow, String resolutionQuality) {
File f = new File(Environment.getExternalStorageDirectory() + "FiltureImages");
if (!f.exists()) {
f.mkdirs();
}
File file = new File(f, fileNameHigh + resolutionQuality + ".png");
if (file.exists()) {
file.delete();
}
File file1 = new File(f, fileNameLow + resolutionQuality + ".png");
if (file1.exists()) {
file1.delete();
}
try {
FileOutputStream high = new FileOutputStream(file);
FileOutputStream low = new FileOutputStream(file1);
bmp.compress(Bitmap.CompressFormat.JPEG, resolutionHigh, high);
bmp.compress(Bitmap.CompressFormat.JPEG, resolutionLow, low);
Toast.makeText(this, "Image save successfully", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Image save falid", Toast.LENGTH_SHORT).show();
}
}
Create a second bitmap with an alternate resolution this way and call scaledBmp.compress() into a new file.
Bitmap scaledBmp = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, false);
How can I put Mediascanner code here? I need to show images on gallery. Tried so many solutions, but nothing worked.
An example with the given code will be helpful:
public void SaveImage(Bitmap bitmap)
{
final File myDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
pref.getGalleryName());
myDir.mkdirs();
// fix
myDir.setExecutable(true);
myDir.setReadable(true);
myDir.setWritable(true);
Random generator = new Random();
int n = 100000;
n = generator.nextInt(n);
final String fname = "Filename" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try
{
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(
_context,
_context.getString(R.string.toast_saved).replace("#",
"\"" + pref.getGalleryName() + "\""),
Toast.LENGTH_SHORT).show();
Log.d(TAG, "Image saved to: " + file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(_context,
_context.getString(R.string.toast_saved_failed),
Toast.LENGTH_LONG).show();
}
}
}
We can't directly call media scanner after version kitkat,it is only limited to system applications.
For updating contents in gallery you need to directly update mediastore database of gallery with required file name.
This is what i did to overcome the issue.
This method is also efficient than Mediascanner,because Mediascanner method requires a lot of cpu resource.
Mediascanner basically search for multimedia contents on our entire storage locations and that may slowdown the device performance
public void saveImageToSDCard(Bitmap bitmap)
{
final File myDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
pref.getGalleryName());
myDir.mkdirs();
Random generator = new Random();
int n = 100000;
n = generator.nextInt(n);
final String fname = "File" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(
_context,
_context.getString(R.string.toast_saved).replace("#",
"\"" + pref.getGalleryName() + "\""),
Toast.LENGTH_SHORT).show();
Log.d(TAG, "Image saved to: " + file.getAbsolutePath());
// follow from here onwards
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA,file.getAbsolutePath());
values.put(MediaStore.Images.Media.MIME_TYPE,"image/jpeg");
_context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(_context,
_context.getString(R.string.toast_saved_failed),
Toast.LENGTH_LONG).show();
}
}
i am trying to download image from internet in original quality. then trying to BitmapFactory.decodeFile() to get the Bitmap
to perform this task i tried this but i am getting this error:
The method decodeFile(String) in the type BitmapFactory is not applicable for the arguments (FileOutputStream)
code:
public void saveImageToSDCard(Bitmap bitmap) {
String dirname = "/Amazing Wallpapers/";
File myDir = new File(Environment.getExternalStorageDirectory()
.getPath() + dirname);
myDir.mkdirs();
String str = currentUrl.substring(currentUrl.lastIndexOf('/') + 1,
currentUrl.length());
String fname = "Wallpaper-" + str + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap = BitmapFactory.decodeFile(out);
out.flush();
out.close();
Toast.makeText(
_context,
_context.getString(R.string.toast_saved).replace("#",
"\"" + pref.getGalleryName() + "\""),
Toast.LENGTH_SHORT).show();
Log.d(TAG, "Wallpaper saved to:" + file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(_context,
_context.getString(R.string.toast_saved_failed),
Toast.LENGTH_SHORT).show();
}
}
You should pass the file name to the function BitmapFactory.decodeFile()instead of the output stream
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.
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.