Android从网络中获取图片
1. 首先要在AndroidManifest.xml文件中添加访问网络的权限:
<uses-permission android:name="android.permission.INTERNET"/>
2. 接着是界面:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="网络图片地址" />
<EditText
android:id="@+id/edit_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="http://a.hiphotos.baidu.com/image/pic/item/b3b7d0a20cf431adb35c8e304936acaf2edd9829.jpg"
/>
<Button
android:id="@+id/btn_get"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="获取图片"
/>
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
3. 然后是Activity中的方法:
public class MainActivity extends Activity {
private Button btn_get;
private EditText edit_address;
private ImageView imageview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
btn_get = (Button) findViewById(R.id.btn_get);
edit_address = (EditText) findViewById(R.id.edit_address);
imageview = (ImageView) findViewById(R.id.imageview);
btn_get.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String path = edit_address.getText().toString();
ImageService imageService = new ImageService();
try {
byte[] data = imageService.getImage(path);
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
imageview.setImageBitmap(bitmap);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "获取失败", 1000).show();
Log.e("ImageError", e.toString());
}
}
});
}
public class ImageService {
public byte[] getImage(String path) throws Exception{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inputStream = conn.getInputStream();
byte[] data = readInputStream(inputStream);
return data;
}
public byte[] readInputStream(InputStream inputStream) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
inputStream.close();
return outputStream.toByteArray();
}
}
}