简体   繁体   English

从 URL 加载图像并保存在 android 中的 memory

[英]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?如何从 URL 加载图像并将其保存在 android 设备的 memory 上? Dont say me use Picasso or oser laibrary.不要说我使用毕加索或 oser 图书馆。 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. 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谢谢你的帮助

PS Sorry me, I can make some mistakes in question because I don`t very good know English. PS对不起,我可能会在问题中犯一些错误,因为我不太懂英语。 This my class:这是我的 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);
    }
}

Try to use this code:尝试使用此代码:

Method for loading image from imageUrlimageUrl加载图片的方法

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: Bitmap保存到外部存储(SD 卡)上的文件,您可以使用以下方法:

    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更新 2

Method getBitmapFromURL() , but ImageView should be updated from UI thread, so You should call getBitmapFromURL() , for example, this way:方法getBitmapFromURL() ,但ImageView应该从 UI 线程更新,所以你应该调用getBitmapFromURL() ,例如,这样:

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();

I had this same issue and I hope this helps.我有同样的问题,我希望这会有所帮助。 First, To download Image from URL into your app, use the code below:首先,要将图像从 URL 下载到您的应用程序中,请使用以下代码:

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { ImageView bmImage; private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }
        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

In order for the image to be displayed inside the app, use the method below in your onCreate method:为了使图像在应用程序中显示,请在 onCreate 方法中使用以下方法:

new DownloadImageTask((ImageView) -your imageview id-).execute(-your URL-); new DownloadImageTask((ImageView) -your imageview id-).execute(-your URL-);

In order for the image to be saved INTERNALLY inside the app/phone, use the code below:为了将图像保存在应用程序/手机内部,请使用以下代码:

@SuppressLint("WrongThread")
        protected void onPostExecute(Bitmap result) {
            if (result != null) {
                File dir = new File(peekAvailableContext().getFilesDir(), "MyImages");
                if(!dir.exists()){
                    dir.mkdir();
                }
                File destination = new File(dir, "image.jpg");

                try {
                    destination.createNewFile();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    result.compress(Bitmap.CompressFormat.PNG, 0, bos);
                    byte[] bitmapdata = bos.toByteArray();

                    FileOutputStream fos = new FileOutputStream(destination);
                    fos.write(bitmapdata);
                    fos.flush();
                    fos.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            bmImage.setImageBitmap(result);
        }

    }

To load the image from the internal storage, use the code below:要从内部存储加载图像,请使用以下代码:

private void loadImageFromStorage(String path)
    {

  

  try {
        File f=new File(path, "image.jpg");
        Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
        ImageView img=(ImageView)findViewById(R.id.businessCard_iv);
        img.setImageBitmap(b);
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }

}

Things to note: 1. path is the a string containing the path of the file.注意事项: 1. path 是一个包含文件路径的字符串。 2. "image.jpg" is the file name so ensure that matches with yours. 2. “image.jpg”是文件名,所以请确保与您的匹配。 3. "MyImages" is a folder in your path which contains the actual saved image. 3. “MyImages”是路径中的一个文件夹,其中包含实际保存的图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM