Android设置拍照或者上传本地图片的示例
程序员文章站
2024-03-02 11:12:52
前几天,我们客户端这边收到了市场部的一个需求,需要在我们订单成交后,我们的客户端有一个上传交易凭证的功能,那么如何在android实现上传图片的这个功能呢?在我进行编码之前...
前几天,我们客户端这边收到了市场部的一个需求,需要在我们订单成交后,我们的客户端有一个上传交易凭证的功能,那么如何在android实现上传图片的这个功能呢?在我进行编码之前,我先问自己几个问题。
第一, 图片是直接选择图库里的,还是需要拍照和选择图片两个选项?
因为在选择图片的时候,会有一个拍照的按钮,也可以实现拍照的功能。
第二, 需不需要本地缓存?
本地缓存值得是,在我们的图片上传后,是否在下次直接显示,而不是从服务器读取。
第三,图片是否需要压缩?
众所周知,图片这种资源,因为体积较大,在网络上传输还是很慢的,所以,我们需要在我们的传输时,适当的对文件的大小进行压缩,那么就要根据我们自身的需求,按照一定的比例来进行压缩。
在思考完这几个问题后,根据我们自己的需求,我们在上传时有两个选项的,一个是拍照,一个是选择图片,另外我们需要做本地缓存,还有,图片上传不需要压缩。
那么我们就可以开始实现了,首先在我们的主fragment里,添加如下代码,如果你是activity,当然也可以。
做一个imageview,作为我们上传的图像。
mpic1 = (imageview) view.findviewbyid(r.id.imageview01); nbsp; mpic1.setonclicklistener(mphotolistener); private view.onclicklistener mphotolistener = new view.onclicklistener() { @override public void onclick(view v) { int id = v.getid(); if (id == r.id.imageview01) { intent popupintent = new intent(getactivity(), popupactivity.class); mphotoid = id; startactivityforresult(popupintent, 1); } } };
然后,我们跳转到另外一个popupactivity,让我们选择,
popupactivity.java
package com.chuanlaoda.android.activity; import java.io.dataoutputstream; import java.io.file; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.net.httpurlconnection; import java.net.url; import java.text.simpledateformat; import java.util.calendar; import java.util.date; import android.app.activity; import android.app.alertdialog; import android.content.activitynotfoundexception; import android.content.dialoginterface; import android.content.intent; import android.graphics.bitmap; import android.graphics.bitmap.compressformat; import android.net.uri; import android.os.bundle; import android.os.environment; import android.provider.mediastore; import android.util.log; import android.view.motionevent; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.imageview; import android.widget.linearlayout; import android.widget.toast; import com.chuanloada.android.r; public class popupactivity extends activity implements onclicklistener { private button btn_take_photo, btn_pick_photo, btn_cancel; private linearlayout layout; private intent intent; private button showlist; private button uploadnow; private string mcurrentphotopath; private bitmap sourcepic; private file dir = null; private string picname = null; private string uploadfile = null; static uri capturedimageuri=null; private bitmap bitmap = null; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.popup); intent = getintent(); btn_take_photo = (button) this.findviewbyid(r.id.btn_take_photo); btn_pick_photo = (button) this.findviewbyid(r.id.btn_pick_photo); btn_cancel = (button) this.findviewbyid(r.id.btn_cancel); layout = (linearlayout) findviewbyid(r.id.pop_layout); layout.setonclicklistener(new onclicklistener() { public void onclick(view v) { // todo auto-generated method stub toast.maketext(getapplicationcontext(), "提示:点击空白地方可以关闭", toast.length_short).show(); } }); btn_cancel.setonclicklistener(this); btn_pick_photo.setonclicklistener(this); btn_take_photo.setonclicklistener(this); } @override public boolean ontouchevent(motionevent event) { finish(); return true; } @override protected void onactivityresult(int requestcode, int resultcode, intent data) { if (resultcode != result_ok) { return; } if (data != null) { if (data.getextras() != null) { bitmap = (bitmap) data.getextras().get("data"); intent.putextras(data.getextras()); intent.putextra("uri", capturedimageuri); intent.putextra("requestcode", requestcode); intent.putextra("image", bitmap); } if (data.getdata() != null) intent.setdata(data.getdata()); } setresult(requestcode, intent); finish(); } @override public void onclick(view v) { switch (v.getid()) { case r.id.btn_take_photo: dispatchtakepictureintent(); break; case r.id.btn_pick_photo: try { intent intent = new intent(); intent.settype("image/*"); intent.setaction(intent.action_get_content); startactivityforresult(intent, 2); } catch (activitynotfoundexception e) { } break; case r.id.btn_cancel: finish(); break; default: break; } } private file createimagefile() throws ioexception { // create an image file name string timestamp = new simpledateformat("yyyymmdd_hhmmss").format(new date()); string imagefilename = "jpeg_" + timestamp + "_"; file storagedir = environment.getexternalstoragepublicdirectory( environment.directory_pictures); file image = file.createtempfile( imagefilename, /* prefix */ ".jpg", /* suffix */ storagedir /* directory */ ); // save a file: path for use with action_view intents mcurrentphotopath = "file:" + image.getabsolutepath(); return image; } private void dispatchtakepictureintent() { intent takepictureintent = new intent(mediastore.action_image_capture); // ensure that there's a camera activity to handle the intent if (takepictureintent.resolveactivity(getpackagemanager()) != null) { // create the file where the photo should go file photofile = null; try { photofile = createimagefile(); } catch (ioexception ex) { // error occurred while creating the file } // continue only if the file was successfully created capturedimageuri = uri.fromfile(photofile); if (photofile != null) { //takepictureintent.putextra(mediastore.extra_output, capturedimageuri); startactivityforresult(takepictureintent, 1); } } } }
popup.xml
<?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:orientation="vertical" > <linearlayout android:id="@+id/pop_layout" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:orientation="vertical" android:layout_alignparentbottom="true" android:background="@drawable/btn_style_alert_dialog_background" > <button android:id="@+id/btn_take_photo" android:layout_marginleft="20dip" android:layout_marginright="20dip" android:layout_margintop="20dip" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="拍照" android:background="@drawable/btn_style_alert_dialog_button" android:textstyle="bold" /> <button android:id="@+id/btn_pick_photo" android:layout_marginleft="20dip" android:layout_marginright="20dip" android:layout_margintop="5dip" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="从相册选择" android:background="@drawable/btn_style_alert_dialog_button" android:textstyle="bold" /> <button android:id="@+id/btn_cancel" android:layout_marginleft="20dip" android:layout_marginright="20dip" android:layout_margintop="15dip" android:layout_marginbottom="15dip" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="取消" android:background="@drawable/btn_style_alert_dialog_cancel" android:textcolor="#ffffff" android:textstyle="bold" /> </linearlayout> </relativelayout>
接下来就是我们需要在我们的主fragment (或者activity)中添加onactivityresult.
public void onactivityresult(int requestcode, int resultcode, intent data) { photo = (imageview) mview.findviewbyid(mphotoid); string pfid=string.valueof(businessdetailsfragment.getposition(mphotoid) + 1); string gsid=string.valueof(mbusinessid); string cur_date = new simpledateformat("yyyy-mm-dd hh:mm:ss").format(new date()); switch (resultcode) { case 1: if (data != null) { uri mimagecaptureuri = (uri) data.getextras().get("uri"); if (mimagecaptureuri != null) { bitmap image; try { //image = mediastore.images.media.getbitmap(this.getactivity().getcontentresolver(), mimagecaptureuri); image = (bitmap) data.getextras().get("image"); string filefullpath = photoapi.savepicstosdcard(image, mfileloc); promptutils.showprogressdialog(getactivity(), "正在上传照片"); mresult = photoapi.uploadfile(gsid, pfid, filefullpath); cache.addlastphotopath(pfid, filefullpath); cache.addlastphotodate(gsid, cur_date); promptutils.dismissprogressdialog(); showdialog(mresult); if (image != null) { photo.setimagebitmap(image); } } catch (exception e) { e.printstacktrace(); } } else { bundle extras = data.getextras(); if (extras != null) { bitmap image = extras.getparcelable("data"); string filefullpath = photoapi.savepicstosdcard(image, mfileloc); promptutils.showprogressdialog(getactivity(), "正在上传照片"); mresult = photoapi.uploadfile(gsid, pfid, filefullpath); promptutils.dismissprogressdialog(); cache.addlastphotopath(pfid, filefullpath); cache.addlastphotodate(gsid, cur_date); showdialog(mresult); if (image != null) { photo.setimagebitmap(image); } } } } break; case 2: if (data != null) { uri mimagecaptureuri = data.getdata(); if (mimagecaptureuri != null) { bitmap image; try { image = mediastore.images.media.getbitmap(this.getactivity().getcontentresolver(), mimagecaptureuri); string filefullpath = getrealpathfromuri(this.getactivity(),mimagecaptureuri); promptutils.showprogressdialog(getactivity(), "正在上传照片"); mresult = photoapi.uploadfile(gsid, pfid, filefullpath); promptutils.dismissprogressdialog(); cache.addlastphotopath(pfid, filefullpath); cache.addlastphotodate(gsid, cur_date); showdialog(mresult); if (image != null) { photo.setimagebitmap(image); } } catch (exception e) { e.printstacktrace(); } } else { bundle extras = data.getextras(); if (extras != null) { string filefullpath = getrealpathfromuri(this.getactivity(),mimagecaptureuri); promptutils.showprogressdialog(getactivity(), "正在上传照片"); mresult = photoapi.uploadfile(gsid, pfid, filefullpath); promptutils.dismissprogressdialog(); cache.addlastphotopath(pfid, filefullpath); cache.addlastphotodate(gsid, cur_date); bitmap image = extras.getparcelable("data"); if (image != null) { photo.setimagebitmap(image); } } } } break; default: break; } }
另外,我们处理图片上传的代码在这里。
class uploadthread extends thread { private string result = ""; private string actionurl; private string uploadfile; public uploadthread(string gsid, string pfid, string uploadfile) { string baseurl = apiconfig.getapihost() + "uploadproof"; this.actionurl=baseurl+"&gsid=" + gsid + "&pfid="+pfid; this.uploadfile = uploadfile; } @override public void run() { string end = "\r\n"; string twohyphens = "--"; string boundary = "*****"; try { url url = new url(actionurl); httpurlconnection con = (httpurlconnection) url.openconnection(); /* 允许input、output,不使用cache */ con.setdoinput(true); con.setdooutput(true); con.setusecaches(false); /* 设置传送的method=post */ con.setrequestmethod("post"); /* setrequestproperty */ con.setrequestproperty("connection", "keep-alive"); con.setrequestproperty("charset", "utf-8"); con.setrequestproperty("content-type", "multipart/form-data;boundary=" + boundary); /* 设置dataoutputstream */ dataoutputstream ds = new dataoutputstream(con.getoutputstream()); ds.writebytes(twohyphens + boundary + end); ds.writebytes("content-disposition: form-data; " + "name=\"gooddship\";filename=\"" + uploadfile + "\"" + end); ds.writebytes(end); /* 取得文件的fileinputstream */ fileinputstream fstream = new fileinputstream(uploadfile); /* 设置每次写入1024bytes */ int buffersize = 1024; byte[] buffer = new byte[buffersize]; int length = -1; /* 从文件读取数据至缓冲区 */ while ((length = fstream.read(buffer)) != -1) { /* 将资料写入dataoutputstream中 */ ds.write(buffer, 0, length); } ds.writebytes(end); ds.writebytes(twohyphens + boundary + twohyphens + end); /* close streams */ fstream.close(); ds.flush(); /* 取得response内容 */ inputstream is = con.getinputstream(); int ch; stringbuffer b = new stringbuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); } /* parse json */ jsonobject jobject = new jsonobject(b.tostring()); int code = jobject.getint("code"); string error = jobject.getstring("error"); string msg = jobject.getstring("msg"); if (code == 1) { /* 将response显示于dialog */ result = "上传成功"; } else result = "上传失败" + error; /* 关闭dataoutputstream */ ds.close(); } catch (exception e) { result = "上传失败" + e; } }
然后就可以了,我们最终的效果如下。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。