Android 开发工具类 23_getImage

时间:2021-06-27 21:43:48

pathText = "http://192.168.1.100:8080/ServerForPicture/wangjialin.jpg"

 import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; public class ImageService { /**
* 获取图片
* @param path 图片路径
* @return
*/
public static Bitmap getImage(String path) throws Exception{ URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET"); if(conn.getResponseCode() == 200){
InputStream inStream = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inStream);
return bitmap;
/*byte[] data = StreamTool.read(inStream);
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
return bitmap;*/
}
return null;
} }

显示

 public void showimage(View v){
String path = pathText.getText().toString();
try {
Bitmap bitmap = ImageService.getImage(path);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), R.string.error, 1).show();
}
}