基本信息
源码名称:android 拍照或者图片上传
源码大小:2.65M
文件格式:.rar
开发语言:Java
更新时间:2015-11-02
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍


package com.zzphoto;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.lidroid.xutils.http.RequestParams;


import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.ImageView;

@SuppressLint("SdCardPath")
public class MainActivity extends Activity {
	private ImageView iv;
	private Bitmap myBitmap;
	RequestParams params = new RequestParams();
	
	/*这是图片上传请求路径,用来进行图片上传,记得更改*/
	String url = "http://192.168.1.3/productImgUpload.php";
	/*这是写死的图片路径,用来进行上传测试,记得更改*/
	private String textURL = "/storage/emulated/legacy/Pictures/ge/z123.png";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		iv = (ImageView) findViewById(R.id.iv);
	}
	
	/**
	 * 点击发送上传图片请求
	 * @param v
	 */
	public void send(View v){
		File testFile = new File(textURL);
		final Map<String, File> filePar = new HashMap<String, File>();
		filePar.put("file", testFile);
		
		//	开线程进行上传请求
		new Thread(new Runnable() {
			public void run() {
				StringBuilder result = HttpUploadFile.sendFile(url,	null, filePar);
				System.out.println("###"   result.toString());
			}
		}).start();
		
		Bitmap bit = BitmapFactory.decodeFile("/storage/emulated/legacy/Pictures/ge/wel_3.png");
		iv.setImageBitmap(bit);
	}
	
	public void onClick(View v) {
		PictureUtil.doPickPhotoAction(MainActivity.this);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Intent intent = new Intent("com.android.camera.action.CROP");
		Uri data2 = null;
		if (data == null) {
			data2 = PictureUtil.getImageUri();
		} else {
			data2 = data.getData();
		}
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case PictureUtil.PHOTO_PICKED_WITH_DATA:
				intent.setDataAndType(data2, "image/*");
				intent.putExtra("crop", true);
				// 设置裁剪尺寸
				intent.putExtra("aspectX", 1);
				intent.putExtra("aspectY", 1);
				intent.putExtra("outputX", 160);
				intent.putExtra("outputY", 130);
				intent.putExtra("return-data", true);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, PictureUtil.getImageCaiUri());
				startActivityForResult(intent, PictureUtil.PHOTO_CROP);
				break;
			case PictureUtil.CAMERA_WITH_DATA:
				intent.setDataAndType(data2, "image/*");
				intent.putExtra("crop", true);
				intent.putExtra("aspectX", 1);
				intent.putExtra("aspectY", 1);
				intent.putExtra("outputX", 160);
				intent.putExtra("outputY", 130);
				intent.putExtra("return-data", true);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, PictureUtil.getImageCaiUri());
				startActivityForResult(intent, PictureUtil.PHOTO_CROP);
				break;
			case PictureUtil.PHOTO_CROP:
				Bundle bundle = data.getExtras(); 
				myBitmap = (Bitmap) bundle.get("data"); 
				Bitmap bitImage = comp(myBitmap);
				
				String fileName = getCharacterAndNumber();
				File file = new File(PictureUtil.PHOTO_DIR, fileName ".png");
				saveMyBitmap(bitImage,file);
				
				iv.setImageBitmap(bitImage);
				
				final Map<String, File> fileParas = new HashMap<String, File>();
				fileParas.put("file", file);
				
				/**
				 * 在这里选择完毕后,直接进行了上传,在logcat中查看结果吧..
				 */
				new Thread(new Runnable() {
					public void run() {
						StringBuilder result = HttpUploadFile.sendFile(url,	null, fileParas);
						System.out.println("###"   result.toString());
					}
				}).start();
				break;

			default:
				break;
			}
		}
	}
	
	//	压缩图片(第二次)
	private Bitmap compressImage(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.PNG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 200) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.PNG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return bitmap;
	}
	
	//	压缩图片(第一次)
    private Bitmap comp(Bitmap image) {  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();         
        image.compress(Bitmap.CompressFormat.PNG, 100, baos);  
        if( baos.toByteArray().length / 1024>200) {//判断如果图片大于200KB,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出    
            baos.reset();//重置baos即清空baos  
            image.compress(Bitmap.CompressFormat.PNG, 50, baos);//这里压缩50%,把压缩后的数据存放到baos中  
        }  
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());  
        BitmapFactory.Options newOpts = new BitmapFactory.Options();  
        //开始读入图片,此时把options.inJustDecodeBounds 设回true了  
        newOpts.inJustDecodeBounds = true;  
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);  
        newOpts.inJustDecodeBounds = false;  
        int w = newOpts.outWidth;  
        int h = newOpts.outHeight;  
        //现在主流手机比较多是800*480分辨率,所以高和宽我们设置为  
        float hh = 160f;//这里设置高度为800f  
        float ww = 130f;//这里设置宽度为480f  
        //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可  
        int be = 1;//be=1表示不缩放  
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放  
            be = (int) (newOpts.outWidth / ww);  
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放  
            be = (int) (newOpts.outHeight / hh);  
        }  
        if (be <= 0)  
            be = 1;  
        newOpts.inSampleSize = be;//设置缩放比例  
        //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了  
        isBm = new ByteArrayInputStream(baos.toByteArray());  
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);  
        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩  
    }  
	
	public void saveMyBitmap(Bitmap mBitmap, File file) {
		ByteArrayOutputStream baos = null;
		try {
			baos = new ByteArrayOutputStream();
			mBitmap.compress(Bitmap.CompressFormat.PNG, 50, baos);
			byte[] bitmapData = baos.toByteArray();
			
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(bitmapData);
			fos.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//	得到系统当前时间并转化为字符串
	@SuppressLint("SimpleDateFormat")
	public static String getCharacterAndNumber() {  
        String rel="";  
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");   
        Date curDate = new Date(System.currentTimeMillis());  
        rel = formatter.format(curDate);     
        return rel;  
    }
}