Android - 在不知道类型的情况下下载图像?

时间:2013-05-28 16:13:15

标签: android http image-processing android-asynctask background-thread

在Android中有没有办法在不知道其类型的情况下下载图像文件?我有这个AsyncTask下载图像并将其设置为位图,但我不想强制任何特定的扩展。相反,我希望声明一组可接受的格式,然后使用唯一的文件名拉取。有什么建议或替代方案吗?

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

}

1 个答案:

答案 0 :(得分:0)

您无需知道下载图像的类型。您可以将图像拉入字节数组,然后根据需要创建所需的图像对象。

以下是下载图片的一些代码:

        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");
        }

然后,如果你想创建一个位图,你可以这样做。

Bitmap bmp=BitmapFactory.decodeByteArray(data,0,data.length);
ImageView image=new ImageView(this);
image.setImageBitmap(bmp);