博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android下载图片/调用系统相机拍照、显示并保存到本地
阅读量:7125 次
发布时间:2019-06-28

本文共 5331 字,大约阅读时间需要 17 分钟。

package com.example.testhttpget;import java.io.BufferedReader;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.InputStream;import java.io.InputStreamReader;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import android.app.Activity;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.os.Message;import android.provider.MediaStore;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.ImageView;import android.widget.TextView;public class MainActivity extends Activity {	ImageView iamgeview = null;		Handler myHandler = new Handler() {          public void handleMessage(Message msg) {                switch (msg.what) {                     case 1:                   	  iamgeview.setImageBitmap((Bitmap)msg.obj);                       break;                }                super.handleMessage(msg);           }      };  	    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                final TextView hello = (TextView)findViewById(R.id.hello);        iamgeview = (ImageView)findViewById(R.id.imageview);                // 子线程网络下载图片        new Thread(){        	public void run(){        		String imgurl = "http://photocdn.sohu.com/20111123/Img326603573.jpg";        		HttpGet mHttpGet = new HttpGet(imgurl);        		//        		 HttpGet mHttpGet = new HttpGet("http://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E7%86%8A%E7%8" +//        		 		"C%AB&step_word=&hs=0&pn=0&spn=0&di=28270682580&pi=&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=404637145%2C3982267385&os=3438506744%2C3869227355&simid=0%2C0&adpicid=0&ln=1975&fr=&fmq=1475036112689_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=&height=&face=undefined&ist=&jit=&cg=&bdtype=11&oriquery=&objurl=http%3A%2F%2Fpic4.40017.cn%2Fscenery%2Fdestination%2F2016%2F07%2F17%2F16%2FNylDjq.jpg" );        		 HttpClient mHtppClient = new DefaultHttpClient();        		 try{        			 // 发送get请求并获得相应对象        			HttpResponse httpRespose = mHtppClient.execute(mHttpGet);        			// 取得消息实体        			HttpEntity entrie = httpRespose.getEntity();        			 // 从消息实体取得输入流        			InputStream inputstream = entrie.getContent();        			// 将输入流转化成BufferedReader        			BufferedReader bufferReader = new BufferedReader(        					new InputStreamReader(inputstream));        			String result = "";        			String line = "";        			//        			for(;(line = bufferReader.readLine())!=null;){//        				result += line ;//        			}//        			hello.setText(result);        			        			Bitmap bitmap = BitmapFactory.decodeStream(inputstream);          			        			saveImg2SDcard(bitmap,"/WebTakePhone.jpg");        			        			Message msg = new Message();         			msg.obj = bitmap;        			msg.what = 1;        			myHandler.sendMessage(msg);        		 }catch(Exception e){//        			 hello.setText("请求错误"+e.toString());        		 };        	}        }.start();                // 调用系统相机拍照并保存图片、展示图片        findViewById(R.id.takephotos).setOnClickListener(new OnClickListener() {						@Override			public void onClick(View v) {				// 调用系统相机				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);		        startActivityForResult(intent,1);			}		});    }    @Override   	protected void onActivityResult(int requestCode, int resultCode, Intent data) {   		super.onActivityResult(requestCode, resultCode, data);   		if(resultCode == Activity.RESULT_OK){   			Bundle bundle = (Bundle)data.getExtras();   			Bitmap bitmap = (Bitmap)bundle.get("data");   			   			saveImg2SDcard(bitmap,"/systemTakePhone.jpg");   		}   	}        private void saveImg2SDcard(Bitmap bitmap,String fileName) {    	FileOutputStream fos;			try {				if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { 					fos = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsoluteFile()+fileName);				}else{					fos = new FileOutputStream(getFilesDir()+fileName);				}				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);				iamgeview.setImageBitmap(bitmap);			} catch (FileNotFoundException e) {				e.printStackTrace();			}	}	@Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}

  

转载于:https://www.cnblogs.com/Jackie-zhang/p/6096242.html

你可能感兴趣的文章
redis学习一, 在mac系统下安装
查看>>
Matrix 矩阵css3
查看>>
Seajs源码解读
查看>>
CSS世界(文档)
查看>>
Laravel.log 文件写入的问题
查看>>
React专题:什么是UI
查看>>
字符图像识别——数字字母混合
查看>>
【Redis学习笔记】2018-06-27 incr、unlink命令
查看>>
【跃迁之路】【515天】程序员高效学习方法论探索系列(实验阶段272-2018.07.05)...
查看>>
SEO优化之浅谈蜘蛛日志
查看>>
如何理解Python装饰器
查看>>
300行Kotlin代码实现的区块链
查看>>
Q3 财报让英伟达股价暴跌超 16%,罪魁祸首却是加密货币
查看>>
如何用Docker编排容器
查看>>
解决git push代码到github上一直提示输入用户名及密码的问题
查看>>
Angular2生命周期钩子函数
查看>>
【Arduino基础教程】RS1307时钟模块
查看>>
10月22日科技联播:饿了么与屈臣氏达成合作;马蜂窝回应数据造假
查看>>
win10电脑桌面便签怎么固定在桌面?
查看>>
[Spring] Web层AOP方式进行参数校验
查看>>