Search code examples
androidfileurlbitmapfileoutputstream

load image from URL and save on memory in android


How to load image from URL and save that on memory of device in android? Dont say me use Picasso or oser laibrary. I need to: If device get internet conection I load image to ImageView from url and save it on memory of device, else I need to load one of save image to imageView. Thank`s for helps

P.S. Sorry me, I can make some mistakes in question because I don`t very good know English. This my class:

public class ImageManager {
    String file_path;
    Bitmap bitmap = null;
    public Bitmap donwoaledImageFromSD() {

       File image = new File(Environment.getExternalStorageDirectory().getPath(),file_path);
       BitmapFactory.Options bmOptions = new BitmapFactory.Options();
       bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);

        return bitmap;
    }

    private void savebitmap() {
        File file = new File("first");
        file_path = file.getAbsolutePath();
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90,fileOutputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void fetchImage(final String url, final ImageView iView) {
        new AsyncTask<String, Void, Bitmap>() {
            protected Bitmap doInBackground(String... iUrl) {

                try {
                    InputStream in = new URL(url).openStream();
                    bitmap = BitmapFactory.decodeStream(in);
                    savebitmap();

                } catch (Exception e) {
                    donwoaledImageFromSD();
                }
                return bitmap;
            }

            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);
                if (iView != null) {
                    iView.setImageBitmap(result);
                }
            }
        }.execute(url);
    }
}

Solution

  • Try to use this code:

    Method for loading image from imageUrl

    public Bitmap getBitmapFromURL(String imageUrl) {
            try {
                URL url = new URL(imageUrl);
                HttpURLConnection connection = (HttpURLConnection) 
    
        url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream inputStream = connection.getInputStream();
                    Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
                    return imageBitmap;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
    

    And You should use it in a separate thread, like that:

    new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Bitmap bitmap = getBitmapFromURL(<URL of your image>);
                        imageView.setImageBitmap(bitmap);
    
                    } catch (Exception e) {
    
                        e.printStackTrace();
                        e.getMessage();
                    }
    
                }
            }).start();
    

    But using Picasso - indeed a better way.

    Update:

    For saving Bitmap to file on external storage (SD card) You can use method like this:

        public static void writeBitmapToSD(String aFileName, Bitmap aBitmap) {
    
                if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    return;
                }
    
                File sdPath = Environment.getExternalStorageDirectory();
                File sdFile = new File(sdPath, aFileName);
    
                if (sdFile.exists()) {
                    sdFile.delete ();
                }
    
                try {
                    FileOutputStream out = new FileOutputStream(sdFile);
                    aBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                    out.flush();
                    out.close();
                } catch (Exception e) {
    
                }
    
            }
    

    Remember that You need

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

    for it.

    And for loading `Bitmap` from file on external storage You can use method like that:
    
    public static Bitmap loadImageFromSD(String aFileName) {
            Bitmap result = null;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                try {
                    FileInputStream fis = new FileInputStream(new File(Environment.getExternalStorageDirectory(), aFileName));
                    result = BitmapFactory.decodeStream(fis);
                    fis.close();
                } catch (FileNotFoundException e) {
                    Log.d(TAG, "loadImageFromSD: " + e.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    

    You need

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

    to do this.

    Update 2

    Method getBitmapFromURL(), but ImageView should be updated from UI thread, so You should call getBitmapFromURL(), for example, this way:

    new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        final Bitmap bitmap = getBitmapFromURL("<your_image_URL>");
    
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                imageView.setImageBitmap(bitmap);
                            }
                        });
    
    
                    } catch (Exception e) {
    
                        e.printStackTrace();
                        e.getMessage();
                    }
    
                }
            }).start();