码迷,mamicode.com
首页 > 移动开发 > 详细

Android 通过网络获取图片的源码

时间:2018-12-16 23:38:39      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:.sh   enc   timeout   oncreate   android   tst   new   button   ace   

将开发过程中经常用到的内容做个备份,如下的资料是关于Android 通过网络获取图片的的内容。

package com.netimg;


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 {
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);

try {
byte[] data = ImageService.getImage(path);
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "获取失败", 1).show();
}


}

}
}





业务类


package com.netimg;

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);
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;
}

}





工具类


package com.netimg;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class StreamTool {

public static byte[] read(InputStream inStream) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len = inStream.read(buffer)) != -1){
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}

}





获取网络权限


<uses-permission android:name="android.permission.INTERNET"/>




 

Android 通过网络获取图片的源码

标签:.sh   enc   timeout   oncreate   android   tst   new   button   ace   

原文地址:https://www.cnblogs.com/qqqqd/p/10128098.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!