将图像URL转换为android中的可绘制资源ID

时间:2015-03-12 02:59:50

标签: android image android-intent android-imageview

我正在使用带有此代码的KenBurnsView库:

mHeaderPicture.setResourceIds(R.drawable.picture0, R.drawable.picture1);

正如您所看到的,它需要可绘制的资源ID。

我想要做的是将所有照片的URL转换为可绘制的资源ID。 照片网址是这样的:

http://example.com/image.jpg
http://example.com/image2.jpg
http://example.com/image3.jpg
http://example.com/image4.jpg

我在这里尝试了这段代码并且无效:

Bitmap drawable_from_url(String url) throws java.net.MalformedURLException, java.io.IOException {
    Bitmap x;

    HttpURLConnection connection = (HttpURLConnection)new URL(url) .openConnection();
    connection.setRequestProperty("User-agent","Mozilla/4.0");

    connection.connect();
    InputStream input = connection.getInputStream();

    x = BitmapFactory.decodeStream(input);
    return x;
}

我已经在网上阅读了很多问题和答案,但我找不到一个好的教程或解决方案。

4 个答案:

答案 0 :(得分:3)

尝试将此库放入您的项目中。它是一个有用的库。 http://square.github.io/picasso/

样本用法:

Picasso.with(context).load("http://example.com/image.jpg").into(imageView);

如何从imageView获取drawable:

Drawable myDrawable = imageView.getDrawable();

答案 1 :(得分:0)

您无法将位图转换为资源ID。资源ID仅适用于APK中的资源。您必须编辑或扩展KenBurnsView类以接受Bitmap对象,例如通过添加如下函数:

public void setBitmaps(Bitmap... bitmaps) {
    for (int i = 0; i < mImageViews.length; i++) {
        mImageViews[i].setImageBitmap(bitmaps[i]);
    }
}

然后您可以使用drawable_from_url()

传递加载的位图

答案 2 :(得分:0)

您忘了将setDoInput添加到连接

public Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

答案 3 :(得分:-1)

添加异步任务...

new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
            .execute(url);
}
public void onClick(View v) {
    startActivity(new Intent(this, IndexActivity.class));
    finish();
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView mHeaderPicture;
public DownloadImageTask(ImageView mHeaderPicture){
        this.mHeaderPicture= mHeaderPicture;
    }  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;
    }

    protected void onPostExecute(Bitmap result) {
        mHeaderPicture.setImageBitmap(result);
    }
}`

确保您在AndroidManifest.xml中设置了以下权限才能访问互联网。

<uses-permission android:name="android.permission.INTERNET" />