How can I save the bitmap correctly the second time?

I want to save my raster file to the cache directory. I am using this code:

try { File file_d = new File(dir+"screenshot.jpg"); @SuppressWarnings("unused") boolean deleted = file_d.delete(); } catch (Exception e) { // TODO: handle exception } imagePath = new File(dir+"screenshot.jpg"); FileOutputStream fos; try { fos = new FileOutputStream(imagePath); bitmap.compress(CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); } catch (FileNotFoundException e) { Log.e("GREC", e.getMessage(), e); } catch (IOException e) { Log.e("GREC", e.getMessage(), e); } } 

It works fine. But if I want to keep different img on the same path, something will go wrong. I mean, it is saved in the same way, but I see this old image, but when I click on the image, I can see the correct image, which I saved the second time.

It may come from the cache, but I don’t want to see the old image, because when I want to share this image with the old whatsapp image, if I send the image, it seems correct.

I want to share the saved image on whatsapp, like this code:

 Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imagePath)); shareIntent.setType("image/jpeg"); startActivityForResult(Intent.createChooser(shareIntent, getResources().getText(R.string.title_share)),whtsapp_result); 

How can i fix this?

early.

+6
source share
2 answers

Finally, I solved my problem as follows:

 Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, getImageUri(context,bitmap_)); shareIntent.setType("image/jpeg"); startActivityForResult(Intent.createChooser(shareIntent, getResources().getText(R.string.title_share)),whtsapp_result); 

v

 public Uri getImageUri(Context inContext, Bitmap inImage) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "TitleC1", null); return Uri.parse(path); } 
+3
source

This is just an assumption, but since you are saving a new image (with the old name or another, which does not matter), you should start scanning the media data in this way so that the media provider is updated with new content.

Look here :

 MediaScannerConnection.scanFile(context, new String[]{imagePath}, null, null); 

Or better yet, wait for the scan to complete:

 MediaScannerConnection.scanFile(context, new String[]{imagePath}, null, new OnScanCompletedListener() { @Override void onScanCompleted(String path, Uri uri) { // Send your intent now. } }); 

In any case, this should be called after , the new file is saved. As I said, I have not tested, and this is just a random assumption.

0
source

All Articles