android上传图片及下载图片并显示

本文详细介绍了如何在Android应用中实现拍照功能,并将拍摄的照片上传至服务器的过程。涉及摄像头调用、图片压缩处理及JSON数据封装等关键技术。

本文参考自: android有进度条的下载图片并且显示图片 , Android实现下载图片并保存到SD卡中

1、项目需要打开摄像头,拍照,然后上传照片。

首先定义一个“拍照”按钮,用来跳转到另一个Activity:

protected void takePhoto() {
		// TODO Auto-generated method stub
		
		String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED))
        { // 检测sd是否可用
            Log.i("exception",
                    "SD card is not avaiable/writeable right now.");
            Toast.makeText(getApplicationContext(), "sd卡无法使用",
				     Toast.LENGTH_SHORT).show();
            return;
        }
       
          File file = new File(
        		Environment.getExternalStorageDirectory().getAbsolutePath()
				+File.separator+"myAQ"+File.separator);
        if(!file.exists())
        	file.mkdirs();// 创建文件夹           
       
		String time = new SimpleDateFormat(
				"yyyyMMddHHmmss").format(new Date());
		fileName = time+".jpg";
		Intent intent = new Intent(PublishNewsActivity.this,TakePhotoActivity.class);	
		intent.putExtra("fileName", fileName);
		startActivityForResult(intent, 10);	
        
	}
在拍照的Activity会打开摄像头,点击拍照按钮可以拍照并返回上一个Activity。

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Bitmap.CompressFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.SurfaceHolder.Callback;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class TakePhotoActivity extends Activity {

	private SurfaceView mSurfaceView;
	private SurfaceHolder mHolder;
	protected Camera camera;
	private Button start;
	private String photoName;
	private int window_width;
	private int window_height;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Window window = getWindow();
		requestWindowFeature(Window.FEATURE_NO_TITLE);//没有标题
		window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
		        WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
		getWindow().setFormat(PixelFormat.TRANSLUCENT);//设置半透明
		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//设置高亮		
		setContentView(R.layout.activity_take_photo);
		
		DisplayMetrics dm = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(dm);
		window_width = dm.widthPixels;//屏幕宽度
		window_height  = dm.heightPixels;//屏幕高度	
		//Log.i("test", window_width+":"+window_height);
		
		start=(Button)findViewById(R.id.take_picture_Button);
		
		mSurfaceView=(SurfaceView)findViewById(R.id.takePicture_surfaceview);//初始预览窗口
		photoName = (String)(this.getIntent().getExtras().getString("fileName"));
		LinearLayout.LayoutParams param  =   
	            new LinearLayout.LayoutParams(
	            		window_height*4/3,window_height);
		param.leftMargin=(window_width-param.width)/2;
		Log.i("test", param.width+":"+param.height+":"+param.leftMargin);
		//findViewById(R.id.takePicture_activity).setLayoutParams(param);
		//mSurfaceView.getHolder().setFixedSize(window_height*4/3,window_height);
		mSurfaceView.setLayoutParams(param);
		

		start.setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						startShot();
										
					}
				}); 
		
		// 绑定初始预览视图
	    mHolder = mSurfaceView.getHolder();
	    mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	    mHolder.addCallback(new Callback() {

	        @Override
	        public void surfaceDestroyed(SurfaceHolder holder) {
	        	
	            camera.stopPreview();
	            camera.release();
	            camera = null; // 记得释放	            
	            mSurfaceView = null;
	            
	        }

	        @Override
	        public void surfaceCreated(SurfaceHolder holder) {
	            try {
	                camera = Camera.open();
	                //Log.i("why","1");
	                Camera.Parameters parameters = camera.getParameters();
	                parameters.setPreviewFrameRate(24); // 每秒24帧
	                parameters.setPictureSize(640, 480);
	                parameters.setPictureFormat(ImageFormat.JPEG);// 设置照片的输出格式
	                parameters.set("jpeg-quality", 100);// 照片质量
	                parameters.setPreviewSize(640, 480);
	                //parameters.setPreviewFormat(ImageFormat.NV21);
	                /* 获取支持的尺寸
	                List<Camera.Size> pszize = parameters.getSupportedPictureSizes(); 
	                
	                if (null != pszize && 0 < pszize.size()) { 
	                    int height[] = new int[pszize.size()]; 
	                    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 
	                    for (int i = 0; i < pszize.size(); i++) { 
	                        Camera.Size size = (Camera.Size) pszize.get(i); 
	                        int sizeheight = size.height; 
	                        int sizewidth = size.width; 
	                        height[i] = sizeheight; 
	                        map.put(sizeheight, sizewidth); 
	                        Log.i("height","h"+sizeheight+"w"+sizewidth);
	                    } 
	                    Arrays.sort(height); 
	                }
	                */
	                camera.setParameters(parameters);
	                camera.setPreviewDisplay(holder);
	                //Log.i("why","2");
	                camera.startPreview();	                
	                //Log.i("why","3");
	            } catch (Exception e) {
	            	camera.release();
	            	Log.i("why",e.getMessage());
	            }
	            
	        }

	        @Override
	        public void surfaceChanged(SurfaceHolder holder, int format,
	                int width, int height) {
	            
	        }
	    });
		
	}
	protected void startShot() {
		
		// TODO Auto-generated method stub
		
		if (camera != null) {
			
			camera.autoFocus(null);
			camera.takePicture(null, null, callback ); 			
		}
		
		
		
	}   
		          


	
	PictureCallback callback=new PictureCallback() {
		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			Bitmap bitmap = BitmapFactory.decodeByteArray(data,
					0, data.length);
			Matrix matrix = new Matrix();
			// 设置缩放
			matrix.postScale(1f, 1f);
			bitmap = Bitmap.createBitmap(bitmap, 0, 0,
					bitmap.getWidth(), bitmap.getHeight(),
					matrix, true);

			String shot_path = Environment.getExternalStorageDirectory().getAbsolutePath()
					+File.separator+"myAQ"+File.separator ;
			String shot_fileName = photoName;
			File shot_out = new File(shot_path);
			if (!shot_out.exists()) {
				shot_out.mkdirs();
			}
			shot_out = new File(shot_path, shot_fileName);
			try {
				FileOutputStream outStream = new FileOutputStream(shot_out);
				bitmap.compress(CompressFormat.JPEG,90,
						outStream);
				outStream.close();
//				Toast.makeText(getApplicationContext(),
//						"拍摄完成~",
//					     Toast.LENGTH_SHORT).show();
//				Intent mIntent = new Intent(Upload_takePicture.this,UploadActivity.class);
//				mIntent.putExtra("photoName", photoName);
//				mIntent.putExtra("userId", user);
				
//				mIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//				startActivity(mIntent);
				Intent i=new Intent();   
	            //请求代码可以自己设置,这里设置成20  
	            setResult(RESULT_OK, i);  
				TakePhotoActivity.this.finish();		
				//camera.startPreview();
			} catch (Exception e) {
				e.printStackTrace();
			}
						
		}
	};

}
拍完照片后,显示在一个imageView上。

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK)
        {
        	 ImageView imageView = (ImageView) findViewById(R.id.publish_imageview);  
	           picPath=Environment.getExternalStorageDirectory().getAbsolutePath()
	       			+File.separator+"myAQ"+File.separator+fileName; 
	           imageView.setImageBitmap(BitmapFactory.decodeFile(picPath)); 
        }
        
    }
发布按钮是如下定义,需要注意的是:先将所有内容放到一个JSONObject(包含图片的编码),然后在将这个JSONObject封装到nameValuePair中,这样的好处是JSON更轻量级。(没有将照片转码的String直接放到nameValuePair中,这样试了一次,出问题了,没有找到问题)

protected void publish_news()
	{
		// TODO Auto-generated method stub
		ArrayList<String> paraName = new ArrayList<String>();
	    ArrayList<String> paraValue = new ArrayList<String>();
	    EditText publish_newstitle=(EditText)findViewById(R.id.publish_newstitle);
	    if(publish_newstitle.getText()==null||publish_newstitle.getText().toString().trim().equals(""))
	    {
	    	
	    	publish_newstitle.setError("请填写新闻标题");
	    	publish_newstitle.requestFocus();
	    	return;
	    }
	    EditText publish_newscontent=(EditText)findViewById(R.id.publish_newscontent);
	    if(publish_newscontent.getText()==null||publish_newscontent.getText().toString().trim().equals(""))
	    {
	    	publish_newscontent.setError("请填写新闻内容");
	    	publish_newscontent.requestFocus();
	    	return;
	    }
	  int x=(int)(latitude*1000000);
	  int y=(int)(longitude*1000000);
	  userID=getSharedPreferences("user_info",MODE_WORLD_READABLE);
	    paraName.add("userId");
	    paraValue.add(userID.getString("userID", null));
	    paraName.add("news_type");
	    paraValue.add(news_type);
	    paraName.add("news_title");
	    paraValue.add(publish_newstitle.getText().toString());
	    paraName.add("news_content");
	    paraValue.add(publish_newscontent.getText().toString());
	    paraName.add("x");
	    paraValue.add(x+"");
	    paraName.add("y");
	    paraValue.add(y+"");

	    try
	    {

	    	File photoFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
					+File.separator+"myAQ"+File.separator+fileName);
    		
    		FileInputStream pfis=new FileInputStream(photoFile);			
    		ByteArrayOutputStream pbaos=new ByteArrayOutputStream();
    		byte[] buffer=new byte[1024];			
    		while(pfis.read(buffer)>0)
    		{
    			pbaos.write(buffer);
    		}
    		
    		String photoData=
    				new String(Base64.encode(pbaos.toByteArray(),Base64.DEFAULT));		    		
    		pfis.close();
    		paraName.add("image");
	    	paraValue.add(photoData);	
	    	 JSONObject jsonObj = new JSONObject();
	         for(int i = 0; i < paraName.size(); i++)
	         {
	         	jsonObj.put(paraName.get(i), paraValue.get(i));
	         }        
	         String jsonString = jsonObj.toString();
	         Log.i("test", "upload:"+jsonString);
	         //指定Post参数
	       //  String encodeString = URLEncoder.encode(jsonString, "utf-8");
	         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
	         nameValuePairs.add(new BasicNameValuePair("data", jsonString));
		   String result = HttpClientTest.doPost(nameValuePairs, Constant.publish_newsURL);	      
	        	Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
	        	PublishNewsActivity.this.finish();
	    }
	    catch(Exception e)
	    {
	    	Log.i("exception","submit:" + e.getMessage());
	    	Toast.makeText(getApplicationContext(), "提交失败",Toast.LENGTH_SHORT).show();
	    }
	    
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值