0
votes

I have to save a png file that is in the drawable folder of Android project structure to the External SD Card. I Have tried doing this but the image was not saved. Could you please help me I'm new to android development.

PS :Yes, the image is in the drawable folder.

package com.example.vishal.demo;

import android.Manifest;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.img);
        File path = Environment.getExternalStorageDirectory();
        File dir = new File(path + "AndroidImageFolder/");
        dir.mkdir();
        File imageFileInSD = new File(dir + "OCRImage.png");
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(imageFileInSD + "");
            bm.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
3

3 Answers

1
votes

Make sure you had added the correct permissions to your manifest file or if using v6.0 methods that you are checking or manifest permissions upon saving

0
votes

Try this code,

File path = Environment.getExternalStorageDirectory();
File dir = new File(path + "/AndroidImageFolder/");
dir.mkdir();

Added permission in manifest

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

Try this code

private void SaveImage(Bitmap finalBitmap) {

String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");    
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ())
  file.delete (); 
try {
    FileOutputStream out = new FileOutputStream(file);
    finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
    out.flush();
    out.close();

} catch (Exception e) {
     e.printStackTrace();
}

}