Android 获取网络图片的代码
2018-07-20 来源:open-open
import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; public class AndroidnetimgActivity extends Activity { /** Called when the activity is first created. */ //定义所使用的组件 private Button button; private EditText editText; private ImageView imagesView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //实例化用到的组件 editText =(EditText)findViewById(R.id.EditText); imagesView = (ImageView)findViewById(R.id.ImageView); button = (Button)findViewById(R.id.Button); //为按钮添加监听事件 button.setOnClickListener(new buttonListener()); } private final class buttonListener implements OnClickListener{ @Override public void onClick(View v) { String path = editText.getText().toString(); System.out.println(path); //通过业务类ImageService的getImage方法得到数据 try { byte[] data = ImageService.getImage(path); Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); imagesView.setImageBitmap(bitmap);//显示图片 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(getApplicationContext(), "获取失败", 1).show(); } } } }
import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class ImageService { public static byte[] getImage(String path) throws Exception { URL url = new URL(path); //基于HTTP协议连接对象 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if(conn.getResponseCode() == 200){ InputStream inStream = conn.getInputStream(); return StreamTool.read(inStream); } return null; } }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇: ios生成三种随机数方法
最新资讯
热门推荐