title: Trouble downloading PNG images in Android
body: <p>I am facing a problem downloading PNG images from my server to my Android app. The problem is specific to PNG images (JPG works fine), and the issue is that the downloaded files are corrupt images. I will explain in more details, below.</p>
  
  <p><strong>Scenario</strong> :</p>
  
  <p>I need to download JPG and PNG images from my server, and display them to the user of the Android app.</p>
  
  <p><strong>Issue</strong> :</p>
  
  <p>The JPG images get downloaded without an issue. But the downloaded PNG files are corrupt. I have double checked the source of the images at my server, and they are proper. Its only the downloaded PNG files, that are corrupt. So, the problem probably lies in the way I am downloading them in Android.</p>
  
  <p><strong>Code Sample</strong> :</p>
  
  <pre><code>URL imageURL;
  File imageFile = null;
  InputStream is = null;
  FileOutputStream fos = null;
  byte[] b = new byte[1024];
  
  try {
      // get the input stream and pass to file output stream
      imageURL = new URL(image.getServerPath());
      imageFile = new File(context.getExternalFilesDir(null), image.getLocalPath());
      fos = new FileOutputStream(imageFile);
  
      // get the input stream and pass to file output stream
      is = imageURL.openConnection().getInputStream();
      // also tried but gave same results :
      // is = imageURL.openStream();
  
      while(is.read(b) != -1)
          fos.write(b);
  
  } catch (FileNotFoundException e) {
  } catch (MalformedURLException e) {
  } catch (IOException e) {
  } finally {
      // close the streams
      try {
          if(fos != null)
              fos.close();
          if(is != null)
              is.close();
      } catch(IOException e){
      }
  }
  </code></pre>
  
  <p>Any pointers on how I can work on this, will be very appreciated.</p>
  
  <p><strong>Note</strong> :</p>
  
  <p>Since this is happening in a service, there are no problems of doing this inside an AsyncTask.</p>