android 获取图片代码

来源:互联网 发布:淘宝网怎么装修店面 编辑:程序博客网 时间:2024/06/06 01:10
package com.hbsi.csdn.picture;


import com.hbsi.csdn.service.ImageService;


import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class showhtmlActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.showhtml);

Button btn2 = (Button) findViewById(R.id.button2);
final TextView tv=(TextView) findViewById(R.id.textView2);

btn2.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
String path="http://www.sohu.com";
try {
byte[] data = ImageService.getImage(path);

tv.setText(new String(data,"GBK"));

} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "出错了,找不到图片",1).show();
Log.e("ERR",e.toString());;
}


}


});
}




}






package com.hbsi.csdn.service;


import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class ImageService {


public static byte[] getImage(String path) throws Exception{
URL url=new URL(path);//得到代表路径的url;
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(20*1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream in=conn.getInputStream();
ByteArrayOutputStream outStream=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len=-1;
while((len=in.read(buffer))!=-1){
outStream.write(buffer,0,len);
}
byte[] data=outStream.toByteArray();//图片的二进制数组
return data;
}


}

原创粉丝点击