Kahn Kah Kahn Kah - 1 year ago 76
Android Question

Android: Saving image on Android Phone from ImageView in a Fragment

So I have this fragment here that looks like:

enter image description here

What I'm trying to do is save the image on my phone (in the file downloads or gallery or ... ).

I have scanned Stackoverflow and the internet but my code is not working. I do not get an error, but I also don't get a picture stored on my phone. What could be my problem? The code I used comes from Stackoverflow.

public class MainFragment extends Fragment {
Button download;
ImageView DownloadImage;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

View v = inflater.inflate(R.layout.fragment_main, container, false);

DownloadImage = (ImageView) v.findViewById(R.id.imageToDownload);
download = (Button) v.findViewById(R.id.buttonDownloadImage);


download.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

return v;

private String saveImageLocally(ImageView iv) {

Bitmap bmp = iv.getDrawingCache();

File storageLoc = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); //context.getExternalFilesDir(null);

File file = new File(storageLoc, "test" + ".jpg");

FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);

scanFile(getActivity(), Uri.fromFile(file));

} catch (FileNotFoundException e) {
} catch (IOException e) {

return "true";

private static void scanFile(Context context, Uri imageUri){
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);



Answer Source

Do you have this permissions in Manifest.xml, because i tried your code and logged its working perfect :

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Actually i tried your code and logged , the result : open failed: EACCES (Permission denied)

Try to look logcats like :

catch (FileNotFoundException e) {
        Log.v("bitmap","not found , "+e.getMessage());
    } catch (IOException e) {
        Log.v("bitmap","io ex , "+e.getMessage());