Android拍照选择图片通过webservice上传图片到到服务器


  1. package com.image.upload;
  2.   
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.IOException;
  7. import java.util.Calendar;
  8.   
  9. import org.kobjects.base64.Base64;
  10. import org.ksoap2.SoapEnvelope;
  11. import org.ksoap2.serialization.SoapObject;
  12. import org.ksoap2.serialization.SoapSerializationEnvelope;
  13. import org.ksoap2.transport.HttpTransportSE;
  14.   
  15. import android.app.Activity;
  16. import android.content.Intent;
  17. import android.database.Cursor;
  18. import android.graphics.BitmapFactory;
  19. import android.net.Uri;
  20. import android.os.Bundle;
  21. import android.os.Environment;
  22. import android.provider.MediaStore;
  23. import android.view.View;
  24. import android.widget.Button;
  25. import android.widget.EditText;
  26. import android.widget.ImageView;
  27. import android.widget.Toast;
  28.   
  29. public class ImageUploadActivity extendsActivity{
  30.     privateButton upload;
  31.     privateImageView image;
  32.     privatestatic final String NAMESPACE ="[color=#0066cc]http://tempuri.org/[/color]"; //[color=#0066cc]http://tempuri.org/[/color]
  33.     // WebService地址
  34.     privatestatic String URL ="[color=#0066cc]http://192.168.2.102:8086/WebService1.asmx?WSDL[/color]";
  35.     privatestatic final String METHOD_NAME ="FileUploadImage";
  36.     privatestatic String SOAP_ACTION ="[color=#0066cc]http://tempuri.org/FileUploadImage[/color]";
  37.     privatestatic String PhotoName="";
  38.     privatefinal String IMAGE_TYPE ="image/*";
  39.     privatefinal int IMAGE_CODE = 0;  
  40.     EditText text;
  41.     /** Called when the activity is first created. */
  42.     @Override
  43.     publicvoid onCreate(Bundle savedInstanceState) {
  44.         super.onCreate(savedInstanceState);
  45.         setContentView(R.layout.main);
  46.        // final EditText text=(EditText)this.findViewById(R.id.text);
  47.         Button makePhoto;
  48.         Button select;
  49.         image = (ImageView)this.findViewById(R.id.image);
  50.         select=(Button)this.findViewById(R.id.select);
  51.         makePhoto=(Button)this.findViewById(R.id.makephoto);
  52.         upload=(Button)this.findViewById(R.id.upload);
  53.         select.setOnClickListener(newButton.OnClickListener()
  54.         {
  55.   
  56.             @Override
  57.             publicvoid onClick(View v) {
  58.                 // TODO Auto-generated method stub
  59.                 Intent getAlbum =new Intent(Intent.ACTION_GET_CONTENT);
  60.                 getAlbum.setType(IMAGE_TYPE);
  61.                 startActivityForResult(getAlbum, IMAGE_CODE);
  62.         
  63.             }
  64.               
  65.         });
  66.         makePhoto.setOnClickListener(newButton.OnClickListener()
  67.         {
  68.   
  69.             @Override
  70.             publicvoid onClick(View v) {
  71.                 // TODO Auto-generated method stub
  72.                  Calendar ca = Calendar.getInstance();
  73.                   intyear = ca.get(Calendar.YEAR);//获取年份
  74.                   intmonth=ca.get(Calendar.MONTH);//获取月份
  75.                   intday=ca.get(Calendar.DATE);//获取日
  76.                   intminute=ca.get(Calendar.MINUTE);//分
  77.                   inthour=ca.get(Calendar.HOUR);//小时
  78.                   intsecond=ca.get(Calendar.SECOND);//秒
  79.                   String fileName=String.valueOf(year)+String.valueOf(month)+String.valueOf(day)+String.valueOf(hour)+String.valueOf(minute)+String.valueOf(second);
  80.                   PhotoName="/mnt/sdcard/"+String.valueOf(year)+String.valueOf(month)+String.valueOf(day)+String.valueOf(hour)+String.valueOf(minute)+String.valueOf(second)+".jpg";
  81.                   Intent intent =new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  82.                     
  83.                   intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(newFile(Environment
  84.                         .getExternalStorageDirectory(),fileName+".jpg")));
  85.                     startActivityForResult(intent,1);
  86.             }
  87.               
  88.               
  89.         });
  90.         upload.setOnClickListener(newButton.OnClickListener(){
  91.             @Override
  92.             publicvoid onClick(View v) {
  93.                 // TODO Auto-generated method stub
  94.                   
  95.                  String str = testUpload();
  96.                     booleanisSussess;
  97.                     try{
  98.                         isSussess = connectWebService(str);
  99.                         if(isSussess==true)
  100.                         {
  101.                               
  102.                              Toast.makeText(getBaseContext(),"图片上传成功!", Toast.LENGTH_LONG).show();
  103.                         }
  104.                         else{
  105.                               
  106.                              Toast.makeText(getBaseContext(),"图片上传失败!", Toast.LENGTH_LONG).show();
  107.                         }
  108.                     }catch (IOException e) {
  109.                         // TODO Auto-generated catch block
  110.                         e.printStackTrace();
  111.                     }
  112.                      
  113.                      
  114.             }
  115.               
  116.               
  117.             publicString testUpload(){   
  118.                 try{
  119.                      
  120.                     String srcUrl =PhotoName;//"/mnt/sdcard/"; //路径     
  121.                     //String fileName = PhotoName+".jpg";  //文件名   
  122.                     FileInputStream fis =new FileInputStream(srcUrl);              
  123.                     ByteArrayOutputStream baos =new ByteArrayOutputStream();   
  124.                     byte[] buffer =new byte[8192];   
  125.                     intcount = 0;   
  126.                     while((count = fis.read(buffer)) >=0){   
  127.                         baos.write(buffer,0, count);   
  128.                     }                  
  129.                     String uploadBuffer =new String(Base64.encode(baos.toByteArray())); //进行Base64编码      
  130.                     returnuploadBuffer;
  131.                      
  132.                 }catch(Exception e){   
  133.                     e.printStackTrace();  
  134.                 }
  135.                 //return soapObject;
  136.                 returnnull;
  137.                   
  138.             }
  139.             privateboolean connectWebService(String uploadBuffer)throws IOException {
  140.                   
  141.                 SoapObject soapObject =new SoapObject(NAMESPACE, METHOD_NAME);
  142.                 soapObject.addProperty("title","");
  143.                 soapObject.addProperty("contect","");
  144.                 soapObject.addProperty("bytestr", uploadBuffer);  //参数2  图片字符串   
  145.                 SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER10);   
  146.                 envelope.setOutputSoapObject(soapObject);
  147.                 envelope.bodyOut = soapObject;   
  148.                 envelope.dotNet =true;   
  149.                 envelope.encodingStyle = SoapSerializationEnvelope.ENC;            
  150.                 HttpTransportSE httpTranstation =new HttpTransportSE(URL);   
  151.                 try{   
  152.                     httpTranstation.call(SOAP_ACTION, envelope);        
  153.                     returntrue;
  154.                      
  155.                 }catch (Exception e) {   
  156.                     e.printStackTrace();
  157.                     returnfalse;
  158.                 }   
  159.                  
  160.                   
  161.             }
  162.             
  163.         });
  164.     }   
  165.     protectedvoid onActivityResult(intrequestCode, intresultCode, Intent data){
  166.         if(resultCode != RESULT_OK) {        //此处的 RESULT_OK 是系统自定义得一个常量
  167.             return;
  168.         }
  169.         if(requestCode == IMAGE_CODE) {
  170.               
  171.             
  172.                try{   
  173.                    Uri selectedImage = data.getData();  
  174.                    String[] filePathColumn = { MediaStore.Images.Media.DATA };  
  175.       
  176.                    Cursor cursor = getContentResolver().query(selectedImage,  
  177.                            filePathColumn,null, null,null);   
  178.                    cursor.moveToFirst();  
  179.       
  180.                    intcolumnIndex = cursor.getColumnIndex(filePathColumn[0]);  
  181.                    String picturePath = cursor.getString(columnIndex);  
  182.                  //  text.setText(picturePath);
  183.                    PhotoName=picturePath;
  184.                    cursor.close();  
  185.                    image.setImageBitmap(BitmapFactory.decodeFile(picturePath));  
  186.                }catch (Exception e) {  
  187.                    // TODO: handle exception   
  188.                    e.printStackTrace();  
  189.                }
  190.                }
  191.         }
  192.     }
复制代码
权限添加:

  1. [font=Courier New]<uses-permission android:name="android.permission.INTERNET"[/font]></uses-permission>    <uses-permission android:name="android.permission.CAMERA"/>   
  2.     <uses-feature android:name="android.hardware.camera"/>   
  3.      <uses-feature android:name="android.hardware.camera.autofocus"android:required="false"/>   
复制代码
main.xml:

  1. <?xml version="1.0"encoding="utf-8"?>
  2. <LinearLayout xmlns:android="[color=#0066cc]http://schemas.android.com/apk/res/android[/color]"
  3.     android:layout_width="match_parent"
  4.     android:layout_height="wrap_content"
  5.     android:orientation="vertical"
  6.     android:background="#87CEFA">
  7.   
  8.     <Button
  9.         android:id="@+id/makephoto"
  10.         android:layout_width="94dp"
  11.         android:layout_height="wrap_content"
  12.         android:text="拍照"/>
  13.   
  14.   
  15.     <ImageView
  16.         android:id="@+id/image"
  17.         android:layout_width="match_parent"
  18.         android:layout_height="384dp"
  19.         android:background="#8B8B7A"/>
  20.   
  21.     <TableLayout
  22.         android:id="@+id/tableLayout1"
  23.         android:layout_width="match_parent"
  24.         android:layout_height="wrap_content">
  25.   
  26.         <TableRow
  27.             android:id="@+id/tableRow1"
  28.             android:layout_width="wrap_content"
  29.             android:layout_height="wrap_content"
  30.             >
  31.   
  32.             <Button
  33.                 android:id="@+id/upload"
  34.                 android:layout_width="95dp"
  35.                 android:layout_height="wrap_content"
  36.                 android:text="上传"/>
  37.   
  38.             <Button
  39.                 android:id="@+id/select"
  40.                 android:layout_width="wrap_content"
  41.                 android:layout_height="wrap_content"
  42.                 android:text="查看"/>
  43.   
  44.         </TableRow>
  45.     </TableLayout>
  46.   
  47. </LinearLayout>
复制代码
webservice:

  1. [font=Courier New]publicstring FileUploadImage(string title, string contect, string bytestr)[/font]        {
  2.             string name ="";
  3.             string mess ="";
  4.             if(bytestr == "")
  5.             {
  6.                 return"失败";
  7.   
  8.             }
  9.             try
  10.             {
  11.                 // Random random = new Random();
  12.                 //string i = random.Next(0, 10000000).ToString();
  13.                 name = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
  14.                 bool flag = StringToFile(bytestr, Server.MapPath("image\\") +"" + name + ".jpg");
  15.                 string filePath ="/image/" + name +".jpg";
  16.                 MODEL.BusinessInfo mo =new MODEL.BusinessInfo();
  17.                 //mo.Title = title;
  18.                // mo.Contents = contect;
  19.                 //mo.Fileds = filePath;
  20.   
  21.                 BLL.BusinessInfo bll =new BLL.BusinessInfo();
  22.                 bll.Add(mo);
  23.                 if(flag == true)
  24.                 {
  25.                     return"成功";
  26.                 }
  27.                 else
  28.                 {
  29.                     return"失败";
  30.                 }
  31.   
  32.             }
  33.             catch(Exception ex)
  34.             {
  35.                 mess = ex.Message;
  36.             }
  37.             if(mess != "")
  38.             {
  39.                 returnmess;
  40.             }
  41.             else
  42.             {
  43.                 return"文件上传成功";
  44.             }
  45.         }
  46.         protectedSystem.Drawing.Image Base64StringToImage(string strbase64)
  47.         {
  48.             try
  49.             {
  50.                 byte[] arr = Convert.FromBase64String(strbase64);
  51.                 MemoryStream ms =new MemoryStream(arr);
  52.                 //Bitmap bmp = new Bitmap(ms);
  53.   
  54.                 ms.Write(arr,0, arr.Length);
  55.                 System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
  56.                 ms.Close();
  57.                 returnimage;
  58.                 //return bmp;
  59.             }
  60.             catch(Exception ex)
  61.             {
  62.                 throwex;
  63.             }
  64.         }
  65.         /// <summary>
  66.         /// 把经过base64编码的字符串保存为文件
  67.         /// </summary>
  68.         /// <param name="base64String">经base64加码后的字符串 </param>
  69.         /// <param name="fileName">保存文件的路径和文件名 </param>
  70.         /// <returns>保存文件是否成功 </returns>
  71.         publicstatic bool StringToFile(string base64String, string fileName)
  72.         {
  73.             //string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + @"/beapp/" + fileName;
  74.   
  75.             System.IO.FileStream fs =new System.IO.FileStream(fileName, System.IO.FileMode.Create);
  76.             System.IO.BinaryWriter bw =new System.IO.BinaryWriter(fs);
  77.             if(!string.IsNullOrEmpty(base64String) && File.Exists(fileName))
  78.             {
  79.                 bw.Write(Convert.FromBase64String(base64String));
  80.             }
  81.             bw.Close();
  82.             fs.Close();
  83.             returntrue;
  84.         }
复制代码
转自:http://blog.csdn.net/yu491290710/article/details/7900830



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值