public class MainActivity extends Activity {
//声明地址
private Button btn;
private ImageView img;
private String url = "http://imgstore04.cdn.sogou.com/app/a/100520024/877e990117d6a7ebc68f46c5e76fc47a";
//在消息队列中实现对控件的更改
private Handler handle = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
System.out.println("111");
Bitmap bmp=(Bitmap)msg.obj;
saveImageToGallery(MainActivity.this, bmp);
// img.setImageBitmap(bmp);
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
img = (ImageView) findViewById(R.id.img);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//新建线程加载图片信息,发送到消息队列中
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Bitmap bmp = getURLimage(url);
Message msg = new Message();
msg.what = 0;
msg.obj = bmp;
System.out.println("000");
handle.sendMessage(msg);
}
}).start();
}
});
}
//加载图片
public Bitmap getURLimage(String url) {
Bitmap bmp = null;
try {
URL myurl = new URL(url);
// 获得连接
HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
conn.setConnectTimeout(6000);//设置超时
conn.setDoInput(true);
conn.setUseCaches(false);//不缓存
conn.connect();
InputStream is = conn.getInputStream();//获得图片的数据流
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return bmp;
}
public static void saveImageToGallery(Context context, Bitmap bmp) {
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
// 首先保存图片
File appDir = new File(Environment.getExternalStorageDirectory(), "qr_coupon");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
}
}
2.调用系统相机和相册进行图片显示。
参考文章:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2013/0731/1494.html
http://www.apkbus.com/blog-56077-47526.html