Android: Saving a bitmap Image - android

I have a button that allows the user to save a bitmap image to his/her gallery in a seperate folder after applying modifications on some of pixel bits as shown below
Random rand= new Random(TimeZone.LONG);
File root=null;
File file = null;
try{
root= Environment.getExternalStorageDirectory();
file = new File(String.format("%s/IMG_%d.png", root.getCanonicalPath(), Math.abs(rand.nextInt()%100000)));
FileOutputStream out = new FileOutputStream(file);
btmImg.compress(Bitmap.CompressFormat.PNG, 100, out);
MediaStore.Images.Media.insertImage(getContentResolver(), file.getCanonicalPath(), file.getName(), file.getName());
out.flush();
out.close();
Toast.makeText(getApplicationContext(), "File is Saved in " + file, 2000).show();
}
The problem is that when I press 'save' button. The image that appears in the user's gallery is not the modified version it is a duplication of the original or something like that. To get the modified version I had to refresh the gallery (by deleting the applications running in the background).
Anyone has an idea about how to solve this !!

Related

Android saves image twice

I'm making a screenshot of my few programmatically but somehow the image is saved in the /TestProject/ folder but also in the normal picture folder. Does anyone have a clue why this is happening. (And is there a change that Android's normal picture folder shows all images all together?)
OutputStream out;
root.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(root.getDrawingCache());
root.setDrawingCacheEnabled(false);
/* Preparation ==================================== */
// Find the SD Card path
File path = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(path.getAbsolutePath() + "/TestProject/");
dir.mkdirs();
/* ================================================= */
// Create a name for the saved image
File file = new File(dir, (new Date().getTime() + ".jpg"));
try {
out = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, (new Date().getTime() + ".jpg"), null);
Toast.makeText(this, "Farm art saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
The insertImage() method also creates a thumbnail for the inserted image. There is a probability that you're seeing the thumbnail and the inserted image.
If you want to force a scan of the image by the media store, you should use the scanFile()[0] method instead.
[0] http://developer.android.com/reference/android/media/MediaScannerConnection.html#scanFile%28java.lang.String,%20java.lang.String%29

Send Image via Intent by WhatsApp - Wrong Image

I thought that this is a popular problem, but I can't find anything related to it. So here is what I want:
I'm trying to send an Image by WhatsApp with the following code:
public static void shareImage(Context context,Bitmap bitmap, String text){
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
share.setPackage("com.whatsapp");
context.startActivity(Intent.createChooser(share, "Share!"));
}
It works fine, for the first time I use the app.. the right image appear in WhatsApp. If I choose another Bitmap with my App, Whatsapp still shows the first Image.
What I did and what I thought caused the problem:
If the temporary file existed, I deleted it by f.delete()
Then I updated the Gallery with MediaScanner, because I thought, that the URI I put in Extra is not up to date...
Fyi: The temporary file contains the right Image: If I choose it with an FileExplorer it shows the right image.. if I try to send the Image.. still the old Image
Does anyone has an idea what the problem might be? Is the Uri wrong? If I print Uri.fromFile(f)it says file:///storage/sdcard0/temporary_file.jpg
Thank you!
Nico
Did you actually send the first image or did you cancel it? I have the same problem and i just realized that the correct image will be send if you continue. I guess the problem is caused by old thumbnail pictures. You could use different filenames.
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file"+ System.currentTimeMillis() +".jpg");
Later you can delete all files starting with "temporary_file"
for (File file : Environment.getExternalStorageDirectory().listFiles()) {
if (file.isFile() && file.getName().startsWith("temporary_file")) file.delete();
}

Android: write photo files on SD Card that are viewable in the gallery

I'm trying to found a way (compatible with android kitkat and next) to write photos on the SD Card and make them visible to the gallery app.
If I use Environment.getExternalStoragePublicDirectory , samsung devices return a path in internal memory (/storage/emulated/0/ ... )
If I use Context.getExternalFilesDirs , there are two results : the first one on internal storage, and the second one on SD Card. Ok, I can write inside and the photo is on the SDCard. But I can't see it in the Galery app :'(
I have tried to write directly on /storage/externalSdCard/DCIM/ but of course I can't since I'm running kitkat.
Ok, I can write inside and the photo is on the SDCard. But I can't see it in the Galery app
First, when you are done writing to the file, call flush(), then getFD().sync(), then close(), all on your FileOutputStream.
Then, use MediaScannerConnection and its scanFile() method to get the newly-written file indexed by the MediaStore.
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 to get image size in bytes from imageview (android)

i am working on an wallpaper app in which i am receiving images from Picasa Web Album in GridView and Full Screen ImageView.
i want to save ImageView loaded image using image bytes size, to prevent duplicate save, but i don't knowhow to get image bytes size from ImageView.`
this is my code:
int intHeight = fullImageView.getHeight();
int intWidth = fullImageView.getWidth();
String dirname2 = "/Amazing Wallpapers HD/";
File myDir2 = new File(Environment.getExternalStorageDirectory()
.getPath() + dirname2);
myDir2.mkdirs();
String fname2 = "image" + intHeight+ intWidth +".jpeg";
File file2 = new File(myDir2, fname2);
if (file2.exists())
file2.delete();
try {
FileOutputStream out = new FileOutputStream(file2);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
Toast.makeText(_context, "failed", Toast.LENGTH_SHORT).show();
}
Note: i am asking about size of image in bytes or kilobytes.
If you are working with Picasa you can simply get photo description which will gives you a lot of unique features in order to use it in your work:
photo.getDescription().getPlainText()
you will find more details here.
You can use BitmapFactory.Options for that. It'll only extract the meta data of the image not the image as a whole.You should be able to get enough data from there to ensure you wont have a duplicate.
For further reading: Android Developers

saving bitmap from arraylist to SD card - saved file unreadable

My situation is as follows: I'm saving multiple bitmaps from an arraylist to a specific folder in my devices SD Card (with success), however, the saved file- when clicked- prompts a message from the phone, stating: "Unable to find application to perform this action." The file size of this file is proportional to that of the bitmap image being saved, so I'm a bit confused, as the device has no problems opening image files, yet cannot open (or identifiy) these as a media file.
Question: What would cause the saved image file (presuming that I have saved it correctly) to exhibit this type of behavior in a device, and how should I resolve this issue?
Extra: the thumbnail of the file is the system provided thumbnail of the two papers on top of each other. The arraylist is being passed from one activity to its current one where the method provided is supplied.
Here is the method invoking the saving of the files to the specified folder /filesdestination:
private void saveImages(){
// to retrieve bitmaps
ArrayList<Bitmap> images = getIntent().getParcelableArrayListExtra("images key");
//to retrieve bitmaps and save in specific order, while also naming them in that order
int loopVal = 0;
int postVal = 9;
while ( loopVal < 9) {
Bitmap Image = images.get(loopVal);
try {
String filedestination = new String(Environment.getExternalStorageDirectory() + "/filedestination");
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File file = new File(filedestination, postVal + ".post_order" + ".jpg" + timeStamp);
File picfile = file;
FileOutputStream fos = new FileOutputStream(picfile);
Image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Throwable e) {
e.printStackTrace();
}
postVal--;
loopVal++;
}
}
Any insight would be appreciated,
-Lucas
i think it cannot read the file type because the timestamp is after the file extension jpg and you are also compressing it as a png, so you might want to change either or, something like this
File file = new File(filedestination, postVal + timeStamp +".post_order" + ".png");
It seems that you are saving a .jpg file compressed as a PNG. That can make the image reader app to misbehave.
Either change Image.compress(Bitmap.CompressFormat.PNG, 100, fos);
to
Image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
or change
File file = new File(filedestination, postVal + ".post_order" + ".jpg" + timeStamp);
to
File file = new File(filedestination, postVal + ".post_order" + ".png" + timeStamp);

Categories

Resources