0

In Android is there any way to download an image file without knowing its type ahead of time? I have this AsyncTask that downloads an image and sets it to a bitmap but I don't want to force any specific extension. Instead, I was hoping to declare a set of acceptable formats then pull using just the unique filename. Any suggestions or alternatives?

public class asyncGetPhoto extends AsyncTask<Void, String, Bitmap>{
    ProgressBar imageProgress;

    @Override
    protected void onPreExecute(){
        imageProgress = (ProgressBar)findViewById(R.id.aboutusImgProgress);
        imageProgress.setVisibility(View.VISIBLE);
    }

    @Override
    protected Bitmap doInBackground(Void... arg0) {
        String url = "SomeDirectory/images/image1.png"
        Bitmap img = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
        return img;
    }

    @Override
    protected void onPostExecute(Bitmap img){
        photo.setImageBitmap(img);
        imageProgress.setVisibility(View.GONE);
    }

}
  • when you download the image, the mime-type should be in the headers – njzk2 May 28 '13 at 16:16
  • But you don't get that until after the file has already been pulled from the server right? – Jonathan Brown May 28 '13 at 17:36
  • this information should be in the header. you can get it by using a HEAD request, or in your GET, before you open the inputstream on the request response. – njzk2 May 29 '13 at 08:21

1 Answers1

0

You don't need to know the type to download an image. You can pull the image into a byte array and then create the image object that you need based on your needs.

Here's some code to download the image:

        URL u = new URL(imageUrl);
        URLConnection uc = u.openConnection();
        int contentLength = uc.getContentLength();
        InputStream in = new BufferedInputStream(uc.getInputStream());
        byte[] data = new byte[contentLength];
        int bytesRead;
        int offset = 0;
        while (offset < contentLength) {
            bytesRead = in.read(data, offset, data.length - offset);
            if (bytesRead == -1)
                break;
            offset += bytesRead;
        }
        in.close();
        if (offset != contentLength) {
            throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
        }

Then if you want to create a bitmap you can down it like this.

Bitmap bmp=BitmapFactory.decodeByteArray(data,0,data.length);
ImageView image=new ImageView(this);
image.setImageBitmap(bmp);
Tishan
  • 141
  • 1
  • 5