Search code examples
androidandroid-imageandroid-internal-storage

android download the image from url store in internal memory then display that image in imageview


I want to download the image from url and store it to internal memory after storing get the image stored in internal memory and display it in imageview


Solution

  • You can use this code to download the image

      URL url = new URL(<your url>);
      InputStream in = new BufferedInputStream(url.openStream());
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      byte[] buf = new byte[1024];
      int n = in.read(buf);
     while (n!=-1)
     {
      out.write(buf, 0, n);
       n=in.read(buf)
      }
     out.close();
     in.close();
     byte[] response = out.toByteArray();
    

    And below code to save it to internal storage

      FileOutputStream fos = new FileOutputStream(filePath);
      fos.write(response);
      fos.close();
    

    where file path for internal storage is

      String filePath=getFilesDir().getPath() + File.separator + "image_" + <some unique identifier like int or string that is different for different images>
    

    ANd to show in imageView use

      File imgFile = new  File(filePath);
    
    if(imgFile.exists()){
    
    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    
    ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
    
    myImage.setImageBitmap(myBitmap);
    
     }
    

    Hope it helps.