1,先写一个布局文件,拍照,选择相片,listview显示照片列表,删除和上传
2,写功能逻辑代码
private File ImageFile ; // 图片的地址
private File VideoFile ; //视频的地址
private String Image_GS = ".jpg" ;
private String Video_GS = ".3gp" ;
List<myphoto> list ;
private Rcxc_Qz_Adapter adapter ;
zxjc zxjc = new zxjc();
String filename [] ;
File files [] ;文件数组
Map<String, Boolean> map ; // 用了封装 选择额结果,多张相片的时候需要记录你选择的相片。
//在baseactivity中需要判断此文件到底有没有,没有的话必须创建
isfile()
public void isFile(){
File f = new File(Environment.getExternalStorageDirectory()+"/Fpmsmsmobile/Image/");
if (!f.exists()) {
f.mkdirs();
}
File f1 = new File(Environment.getExternalStorageDirectory()+"/Fpmsmsmobile/Video/");
if (!f1.exists()) {
f1.mkdirs();
}
File f2 = new File(Environment.getExternalStorageDirectory()+"/Fpmsmsmobile/ImageThumbnil/");
if (!f2.exists()) {
f2.mkdirs();
}
File f3 = new File(Environment.getExternalStorageDirectory()+"/Fpmsmsmobile/ImageThumbnils/");
if (!f3.exists()) {
f3.mkdirs();
}
File f4 = new File(Environment.getExternalStorageDirectory()+"/Fpmsmsmobile/Signature/");
if (!f4.exists()) {
f4.mkdirs();
}
}
map = new HashMap<String, Boolean>();
//获取屏幕分辨率
DisplayMetrics dm = new DisplayMetrics();
//dm = getResources().getDisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
xdpi = dm.widthPixels;
//点击拍照的时候
qz_z.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!CommonUtils.checkSdCard()) {
toast(System.currentTimeMillis(), "请插入内存卡!");
return ;
}
Time = System.currentTimeMillis() ;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 0);
// 获取 sd 卡的位置 Environment.getExternalStorageDirectory()
Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"/Fpmsmsmobile/Image/image_"+Time+Image_GS));
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, 0);
}
});
//点击选择相片的时候
qz_s.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
});
//拍照或者选择相片完成后需要执行的操作
@Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
// TODO Auto-generated method stub
super.onActivityResult(arg0, arg1, arg2);
if (arg0 == 0) { // 获取拍照返回的值
//这里要保存相片到指定文件夹
ImageFile = new File(Environment.getExternalStorageDirectory(),"/Fpmsmsmobile/Image/image_"+Time+Image_GS);
if (ImageFile.exists()){
mDialogshow(KsjcQzActivity.this,"正在保存", "保存中,请稍后·····");
//mDialogshow("正在上传", "上传中,请稍后·····");
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
BitmapUtils.saveBitmap(ImageFile.getPath(), bh,"rilt");
h.sendEmptyMessage(2);
}
}).start();
}
}else if(arg0 == 1){
if (arg2 != null) {
Uri uri = arg2.getData();
final String path = UriToPath(uri);
//mDialogshow("正在上传", "上传中,请稍后·····");
mDialogshow(KsjcQzActivity.this,"正在保存", "保存中,请稍后·····");
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
BitmapUtils.saveBitmap(path, bh,"rilt");
h.sendEmptyMessage(2);
}
}).start();
}
}
//点击上传的时候
update.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (files != null) {
mDialogshow(KsjcQzActivity.this,"正在保存", "保存中,请稍后·····");
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (int j = 0; j < files.length; j++) {
if (map.get(j+"")) {
String baos = null ;
try {
//这里将相片转化为流文件 并且文件加密
baos = BitmapUtils.encodeBase64File( files[j].getPath());
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
//String result = rcxc.Uploadxcqzb(userid, userpassword, bsh, "照片", date, baos);
//zfrybhid, password, guidbh, zbbh, filetype, filename, filedate, filecontent
String result = "" ;
//上传相片
String guid = UUID.randomUUID().toString();
result = spyx.Add_ksjc_qkb_qz(zfrybh, mima, guid,bh,zfrybh, "照片", baos, date);
boolean isTrue = false ;
try {
Integer.parseInt(result);
isTrue = true ;
} catch (Exception e) {
// TODO: handle exception
h.sendEmptyMessage(5);
isTrue = false ;
}
if (isTrue) {
files[j].delete();
}
}
}
h.sendEmptyMessage(4);
}
}).start();
}
}
});
//显示相片的listview还需要写一个adapter
class Rcxc_Qz_Adapter extends BaseAdapter{
@Override
public int getCount() {
// TODO Auto-generated method stub
if (files != null) {
return files.length ;
}else {
return 0 ;
}
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
view = LayoutInflater.from(KsjcQzActivity.this).inflate(R.layout.zxjc_qz_adapter, null);
ImageView image = (ImageView) view.findViewById(R.id.rcjc_qz_adapter_image);
TextView type = (TextView) view.findViewById(R.id.rcjc_qz_adapter_type);
TextView guid = (TextView) view.findViewById(R.id.rcjc_qz_adapter_guid);
final CheckBox check = (CheckBox) view.findViewById(R.id.rcjc_qz_adapter_check);
/*hn_spsc_xcqzb qzb = list.get(position);
if (qzb.filetype.equals("照片")) {
BitmapFactory.Options opts = new Options();
opts.inSampleSize = 5 ;
Bitmap bit = BitmapFactory.decodeByteArray(qzb.filecontent, 0, qzb.filecontent.length,opts) ;
image.setImageBitmap(bit);
}else {
image.setImageResource(R.drawable.zygg);
}
type.setText("类型:"+qzb.filetype);
guid.setText("时间:"+qzb.filedate);*/
BitmapFactory.Options opts = new Options();
opts.inSampleSize = 5 ;
Bitmap bit = BitmapFactory.decodeFile(files[position].getPath(), opts) ;
image.setImageBitmap(bit);
type.setText("类型:"+"照片");
try {
Date date = new Date(Long.parseLong(filename[position].split("_")[2]));
String d ;
if (xdpi > 799) {
d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}else {
d = new SimpleDateFormat("yyyy-MM-dd").format(date);
}
guid.setText("时间:"+d);
//guid.setText("时间:"+filename[position].split("_")[2]);
} catch (Exception e) {
// TODO: handle exception
guid.setText("时间:");
}
check.setChecked(map.get(position+""));
check.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//点击选择框记录当前所选择的值
map.put(position+"", check.isChecked());
}
});
return view;
}
}
//相片操作经常需要将uri转化为路径
//将 URi 转换成 绝对路径
private String UriToPath(Uri uri){
String [] projection = { MediaStore.Images.Media.DATA } ;
@SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(index);
return path ;
}
// 将文件 加密
public static String encodeBase64File(String p) throws Exception {
String path = bitmapPath(p);
File file = new File(path);
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int)file.length()];
inputFile.read(buffer);
inputFile.close();
//System.out.println(android.util.Base64.encodeToString(buffer,Base64.DEFAULT));
return android.util.Base64.encodeToString(buffer,Base64.DEFAULT);
}
//拍照完成或者选取相片以后生成缩略图显示在listview中
private void refresh(){
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
File file = new File(Environment.getExternalStorageDirectory()+"/Fpmsmsmobile/ImageThumbnil/");
filename = file.list() ;
files = file.listFiles();
for (int i = 0; i < files.length; i++) {
map.put(i+"", false);
}
if (files != null) {
myLog("获取数据 成功");
h.sendEmptyMessage(0); // 获取数据 成功
}else {
myLog("获取数据 失败");
h.sendEmptyMessage(1); // 获取数据 失败
}
}
}).start();
}
这里还生成缩略图在另外一个文件中
public static void saveBitmap(String imagefile,String bsh,String riOrzx){
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片,此时把options.inJustDecodeBounds 设回true了 不加载图片
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(imagefile,newOpts);//此时返回bm为空
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
//现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
float hh = 800f;//这里设置高度为800f
float ww = 480f;//这里设置宽度为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了
bitmap = BitmapFactory.decodeFile(imagefile, newOpts);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 50;
while ( (baos.toByteArray().length / 1024) > 100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset();//重置baos即清空baos
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
options -= 5;//每次都减少5
if (options == 0) {
break ;
}
}
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
//File file1 = new File(Environment.getExternalStorageDirectory()+"/Foodproductionofhn/ImageThumbnil/"+riOrzx+"_"+bsh+"_"+date+"_.jpg");
File file = QuZheng.getQM(riOrzx+"_"+bsh+"_"+System.currentTimeMillis(),"qz");
File file1 = QuZheng.getQM("ss","qm");
try {
FileOutputStream os = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, options, os);
os.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream os = new FileOutputStream(file1);
bitmap.compress(CompressFormat.JPEG, options, os);
os.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}