Save an image from a url

2019-02-20 11:36发布

问题:

I want to save an image from a URL with a button in my code i have create the destination folder, but I have tried various codes to save a picture but do not work nothing :

public class B_X extends Activity {   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bx);

        Button buttonSetWallpaper = (Button)findViewById(R.id.bSetWall);
        buttonSetWallpaper.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                File folder = new File(Environment.getExternalStorageDirectory() + "/PerfectAss/");
                boolean success = false;
                if (!folder.exists()) {
                    success = folder.mkdirs();
                }

                if (!success) {
            } else {
            }

                 Toast.makeText(getApplicationContext(), "The image has been saved", Toast.LENGTH_LONG).show();
                    URL url = new URL ("http://bitsparrow.altervista.org/wp-content/uploads/2013/04/5.jpg");
                    InputStream input = url.openStream();
                     try {

                       File storagePath = Environment.getExternalStorageDirectory();
                       OutputStream output = new FileOutputStream (storagePath + "/myImage.png");
                       try {
                            byte[] buffer = new byte[1500];
                             int bytesRead = 0;
                             while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
                             output.write(buffer, 0, bytesRead);
                             }
                             } finally {
                               output.close();
                              }
                              } finally {
                              input.close();
                              }

Please help me fix this code.

回答1:

use this way its easy: its save file in "sdcard/dhaval_files/". just replace your folder name and give permission write_external_storage in android manifest file.

public void file_download(String uRl) {
        File direct = new File(Environment.getExternalStorageDirectory()
                + "/dhaval_files");

        if (!direct.exists()) {
            direct.mkdirs();
        }

        DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);

        Uri downloadUri = Uri.parse(uRl);
        DownloadManager.Request request = new DownloadManager.Request(
                downloadUri);

        request.setAllowedNetworkTypes(
                DownloadManager.Request.NETWORK_WIFI
                        | DownloadManager.Request.NETWORK_MOBILE)
                .setAllowedOverRoaming(false).setTitle("Demo")
                .setDescription("Something useful. No, really.")
                .setDestinationInExternalPublicDir("/dhaval_files", "test.jpg");

        mgr.enqueue(request);

    }


回答2:

have you include permission into your manifest file

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

And try this code

Or then try this code,it will work

URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();

try {
    //The sdcard directory e.g. '/sdcard' can be used directly, or 
    //more safely abstracted with getExternalStorageDirectory()
    File storagePath = Environment.getExternalStorageDirectory();
    OutputStream output = new FileOutputStream (storagePath + "/myImage.png");

    try {
        byte[] buffer = new byte[aReasonableSize];
        int bytesRead = 0;

        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
            output.write(buffer, 0, bytesRead);
        }
    } finally { output.close(); }
} finally { input.close(); }