`
wodamazi
  • 浏览: 1419589 次
文章分类
社区版块
存档分类
最新评论

Android开发下载图片展示

 
阅读更多

  1.普通的下载方式

  布局文件:
  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">

   <ImageView android:src="@drawable/icon"
   android:layout_width="wrap_content"
   android:id="@+id/imgPic"
   android:layout_gravity="center|center_vertical"
   android:layout_height="fill_parent">
   </ImageView>

  </LinearLayout>

  java文件:
  public class DownloadImage extends Activity {
  private ImageView imgPic;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.download_image);
  imgPic = (ImageView) findViewById(R.id.imgPic);
  String url = "图片文件地址"
  loadRmoteImage(url);
  }

  /**
   * @param imgUrl
   * 远程图片文件的URL
   *
   * 下载远程图片
   */
  private void loadRmoteImage(String imgUrl) {
  URL fileURL = null;
  Bitmap bitmap = null;
  try {
  fileURL = new URL(imgUrl);
  } catch (MalformedURLException err) {
  err.printStackTrace();
  }
  try {
  HttpURLConnection conn = (HttpURLConnection) fileURL
  .openConnection();
  conn.setDoInput(true);
  conn.connect();
  InputStream is = conn.getInputStream();
  int length = (int) conn.getContentLength();
  if (length != -1) {
  byte[] imgData = new byte[length];
  byte[] buffer = new byte[512];
  int readLen = 0;
  int destPos = 0;
  while ((readLen = is.read(buffer)) > 0) {
  System.arraycopy(buffer, 0, imgData, destPos,

  readLen);
  destPos += readLen;
  }
  bitmap = BitmapFactory.decodeByteArray(imgData, 0,
  imgData.length);
  }
  } catch (IOException e) {
  e.printStackTrace();
  }
  imgPic.setImageBitmap(bitmap);
  }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics