android獲取網(wǎng)絡圖片

字號:


    public static Bitmap getImage(String Url) throws Exception {
    try {
    URL url = new URL(Url);
    String responseCode = url.openConnection().getHeaderField(0);
    if (responseCode.indexOf("200") < 0)
    throw new Exception("圖片文件不存在或路徑錯誤,錯誤代碼:" + responseCode);
    return BitmapFactory.decodeStream(url.openStream());
    } catch (IOException e) {
    // TODO Auto-generated catch block
    throw new Exception(e.getMessage());
    }
    }
    此類返回的是一個Bitmap的對象,
    下面是對類的一個簡單調用:
    直接上代碼:
    Bitmap mBitmap ;
    // 直接獲取圖片:
    private void RefreshDB() {
    try {
    sendMSG(Declare.START, "正在加載圖片......");
    mBitmap = DownFile.getImage(圖片地址);
    sendMSG(Declare.STOP, "");
    } catch (Exception e) {
    // TODO Auto-generated catch block
    sendMSG(Declare.ERROR, e.getMessage());
    }
    這里帶有一個簡單的滾動條,表示當前程序正在執(zhí)行,通過發(fā)送消息的方式實現(xiàn)的,具體不再寫了,那個消息無頭此核心代碼的實現(xiàn).
    在加載完成后執(zhí)行:
    mImageView1.setImageBitmap(mBitmap);