问题
I want to save my bitmap to cache directory. I use 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 s working fine. But if I want to save different img to same path, something goes wrong. I mean it is saved to same path but I see it old image, but when I click the image I can see the correct image which I saved second time.
Maybe its come from cache but I do not want to see old image because when I want to share that image with whatsapp old image seen , if i send the image it seems correct.
I want to share 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 it?
thanks in advance.
回答1:
Finally I solved my problem like this:
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);
}
回答2:
This is just a guess, but since you save a new image (with the old name, or another, that’s not relevant) you should fire a media scan to that path so that the media provider is updated with new content.
See here:
MediaScannerConnection.scanFile(context, new String[]{imagePath}, null, null);
Or even better, wait for the scan to be completed:
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 guess.
来源:https://stackoverflow.com/questions/37641409/how-can-i-save-my-bitmap-correctly-for-second-time