Android设置拍照或者上传本地图片的示例

Android设置拍照或者上传本地图片的示例,第1张

概述前几天,我们客户端这边收到了市场部的一个需求,需要在我们订单成交后,我们的客户端有一个上传交易凭证的功能,那么如何在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,Intent data) {     photo = (ImageVIEw) mVIEw.findVIEwByID(mPhotoID);     String pfID=String.valueOf(BusinessDetailsFragment.get@R_403_4612@(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(),fileFullPath);             PromptUtils.dismissprogressDialog();             Cache.addLastPhotopath(pfID,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(),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(),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-dis@R_403_4612@: 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,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;     }   } 

然后就可以了,我们最终的效果如下。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android设置拍照或者上传本地图片的示例全部内容,希望文章能够帮你解决Android设置拍照或者上传本地图片的示例所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1141386.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存