将图像从Web加载到图库中

时间:2012-08-02 13:23:59

标签: android

我使用以下代码制作图片库,但我想使用网络上的图片而不是SD卡。有没有办法做到这一点?目前,代码需要和图像的整数值。或者我是否必须先将图像下载到SD?

    public class viewimages extends Activity {

private Gallery gallery;
private ImageView imgView;

private Integer[] Imgid = {
        R.drawable.a_1, R.drawable.a_2, R.drawable.a_3, R.drawable.a_4
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.viewimages);

    imgView = (ImageView)findViewById(R.id.ImageView01);    
    imgView.setImageResource(Imgid[0]);

     gallery = (Gallery) findViewById(R.id.examplegallery);
     gallery.setAdapter(new AddImgAdp(this));

     gallery.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView parent, View v, int position, long id) {
            imgView.setImageResource(Imgid[position]); 
        }
    });


}

public class AddImgAdp extends BaseAdapter {
    int GalItemBg;
    private Context cont;

    public AddImgAdp(Context c) {
        cont = c;
        TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
        GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
        typArray.recycle();
    }

    public int getCount() {
        return Imgid.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imgView = new ImageView(cont);

        imgView.setImageResource(Imgid[position]);
        imgView.setLayoutParams(new Gallery.LayoutParams(80, 70));
        imgView.setScaleType(ImageView.ScaleType.FIT_XY);
        imgView.setBackgroundResource(GalItemBg);

        return imgView;
    }
}

   }

1 个答案:

答案 0 :(得分:2)

您可以这样做:

URL url = new URL("http://www.website.com/image.jpg");
Bimtap bmp = BitmapFactory.decodeStream(url.openConnection()
                    .getInputStream());

然后,您需要将“setImageResource”的位置更改为“setImageBitmap”,并在下载并加载后提供“bmp”对象。

[编辑]

确保您的Android清单具有互联网权限也很重要。

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

[编辑评论问题]

如果你想对多个图像执行此操作,并且图像不是基于id_number(基本上如果图像不像0001.jpg,0002.jpg等),则创建一个字符串ArrayList,保存所有项目的名称,然后迭代它。如,

List<String> imageNames = new ArrayList<String>();
imageNames.add("image.jpg");
imageNames.add("thisPhoto.jpg");
//etc. until you've added all images

for (int i = 0; i < imageNames.size(); i++){
    URL url = new URL("http://www.website.com/" + imageNames.get(i));
    Bimtap bmp = BitmapFactory.decodeStream(url.openConnection()
                    .getInputStream());
}

希望有所帮助