安卓实现拍照、在手机中选择图片通过webservice上传图片到服务器 .

安卓代码:
package com.image.upload;
  
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Calendar;
  
import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
  
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
  
public class ImageUploadActivity extends Activity{
     private Button upload;
     private ImageView image;
     private static final String NAMESPACE = "http://tempuri.org/" ; //http://tempuri.org/
     // WebService地址 
     private static String URL = "http://192.168.2.102:8086/WebService1.asmx?WSDL"
     private static final String METHOD_NAME = "FileUploadImage" ;
     private static String SOAP_ACTION = "http://tempuri.org/FileUploadImage"
     private static String PhotoName= "" ;
     private final String IMAGE_TYPE = "image/*" ;
     private final int IMAGE_CODE = 0
     EditText text;
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.main);
        // final EditText text=(EditText)this.findViewById(R.id.text);
         Button makePhoto;
         Button select;
         image = (ImageView) this .findViewById(R.id.image);
         select=(Button) this .findViewById(R.id.select);
         makePhoto=(Button) this .findViewById(R.id.makephoto);
         upload=(Button) this .findViewById(R.id.upload);
         select.setOnClickListener( new Button.OnClickListener()
         {
  
             @Override
             public void onClick(View v) {
                 // TODO Auto-generated method stub
                 Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
                 getAlbum.setType(IMAGE_TYPE);
                 startActivityForResult(getAlbum, IMAGE_CODE);
        
             }
              
         });
         makePhoto.setOnClickListener( new Button.OnClickListener()
         {
  
             @Override
             public void onClick(View v) {
                 // TODO Auto-generated method stub
                  Calendar ca = Calendar.getInstance();
                   int year = ca.get(Calendar.YEAR); //获取年份
                   int month=ca.get(Calendar.MONTH); //获取月份
                   int day=ca.get(Calendar.DATE); //获取日
                   int minute=ca.get(Calendar.MINUTE); //分
                   int hour=ca.get(Calendar.HOUR); //小时
                   int second=ca.get(Calendar.SECOND); //秒
                   String fileName=String.valueOf(year)+String.valueOf(month)+String.valueOf(day)+String.valueOf(hour)+String.valueOf(minute)+String.valueOf(second);
                   PhotoName= "/mnt/sdcard/" +String.valueOf(year)+String.valueOf(month)+String.valueOf(day)+String.valueOf(hour)+String.valueOf(minute)+String.valueOf(second)+ ".jpg" ;
                   Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    
                   intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile( new File(Environment
                         .getExternalStorageDirectory(),fileName+ ".jpg" )));
                     startActivityForResult(intent, 1 );
             }
              
              
         });
         upload.setOnClickListener( new Button.OnClickListener(){
             @Override
             public void onClick(View v) {
                 // TODO Auto-generated method stub
                  
                  String str = testUpload(); 
                     boolean isSussess;
                     try {
                         isSussess = connectWebService(str);
                         if (isSussess== true )
                         {
                              
                              Toast.makeText(getBaseContext(), "图片上传成功!" , Toast.LENGTH_LONG).show(); 
                         }
                         else {
                              
                              Toast.makeText(getBaseContext(), "图片上传失败!" , Toast.LENGTH_LONG).show(); 
                         }
                     } catch (IOException e) {
                         // TODO Auto-generated catch block
                         e.printStackTrace();
                     }
                      
                      
             }
              
              
             public String testUpload(){   
                 try {
                      
                     String srcUrl =PhotoName; //"/mnt/sdcard/"; //路径    
                     //String fileName = PhotoName+".jpg";  //文件名    
                     FileInputStream fis = new FileInputStream(srcUrl);              
                     ByteArrayOutputStream baos = new ByteArrayOutputStream();   
                     byte [] buffer = new byte [ 8192 ];   
                     int count = 0 ;   
                     while ((count = fis.read(buffer)) >= 0 ){   
                         baos.write(buffer, 0 , count);   
                     }                  
                     String uploadBuffer = new String(Base64.encode(baos.toByteArray()));  //进行Base64编码      
                     return uploadBuffer;
                     
                 } catch (Exception e){   
                     e.printStackTrace();  
                 }
                 //return soapObject;
                 return null ;
                  
             }
             private boolean connectWebService(String uploadBuffer) throws IOException {
                  
                 SoapObject soapObject = new SoapObject(NAMESPACE, METHOD_NAME);
                 soapObject.addProperty( "title" , "" );
                 soapObject.addProperty( "contect" , "" );
                 soapObject.addProperty( "bytestr" , uploadBuffer);   //参数2  图片字符串   
                 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);   
                 envelope.setOutputSoapObject(soapObject);
                 envelope.bodyOut = soapObject;   
                 envelope.dotNet = true ;   
                 envelope.encodingStyle = SoapSerializationEnvelope.ENC;            
                 HttpTransportSE httpTranstation = new HttpTransportSE(URL);   
                 try {   
                     httpTranstation.call(SOAP_ACTION, envelope);        
                     return true ;
                      
                 } catch (Exception e) {   
                     e.printStackTrace();
                     return false ;
                 }    
                 
                  
             }
             
         });
     }   
     protected void onActivityResult( int requestCode, int resultCode, Intent data){
         if (resultCode != RESULT_OK) {        //此处的 RESULT_OK 是系统自定义得一个常量
             return ;
         }
         if (requestCode == IMAGE_CODE) {
              
             
                try {  
                    Uri selectedImage = data.getData();  
                    String[] filePathColumn = { MediaStore.Images.Media.DATA };  
       
                    Cursor cursor = getContentResolver().query(selectedImage,  
                            filePathColumn, null , null , null );  
                    cursor.moveToFirst();  
       
                    int columnIndex = cursor.getColumnIndex(filePathColumn[ 0 ]);  
                    String picturePath = cursor.getString(columnIndex);  
                  //  text.setText(picturePath);
                    PhotoName=picturePath;
                    cursor.close();  
                    image.setImageBitmap(BitmapFactory.decodeFile(picturePath));  
                } catch (Exception e) {  
                    // TODO: handle exception   
                    e.printStackTrace();  
                }
                }
         }
     }
权限添加:
  <uses-permission android:name= "android.permission.INTERNET" ></uses-permission>
     <uses-permission android:name= "android.permission.CAMERA" />   
     <uses-feature android:name= "android.hardware.camera" />  
      <uses-feature android:name= "android.hardware.camera.autofocus" android:required= "false" />  
main.xml:
<?xml version= "1.0" encoding= "utf-8" ?>
<LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
     android:layout_width= "match_parent"
     android:layout_height= "wrap_content"
     android:orientation= "vertical"
     android:background= "#87CEFA" >
  
     <Button
         android:id= "@+id/makephoto"
         android:layout_width= "94dp"
         android:layout_height= "wrap_content"
         android:text= "拍照" />
  
  
     <ImageView
         android:id= "@+id/image"
         android:layout_width= "match_parent"
         android:layout_height= "384dp" 
         android:background= "#8B8B7A" />
  
     <TableLayout
         android:id= "@+id/tableLayout1"
         android:layout_width= "match_parent"
         android:layout_height= "wrap_content" >
  
         <TableRow
             android:id= "@+id/tableRow1"
             android:layout_width= "wrap_content"
             android:layout_height= "wrap_content" 
             >
  
             <Button
                 android:id= "@+id/upload"
                 android:layout_width= "95dp"
                 android:layout_height= "wrap_content"
                 android:text= "上传" />
  
             <Button
                 android:id= "@+id/select"
                 android:layout_width= "wrap_content"
                 android:layout_height= "wrap_content"
                 android:text= "查看" />
  
         </TableRow>
     </TableLayout>
  
</LinearLayout>
webservice:
   public string FileUploadImage(string title, string contect, string bytestr)
         {
             string name = "" ;
             string mess = "" ;
             if (bytestr == "" )
             {
                 return "失败" ;
  
             }
             try
             {
                 // Random random = new Random();
                 //string i = random.Next(0, 10000000).ToString();
                 name = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
                 bool flag = StringToFile(bytestr, Server.MapPath( "image\\" ) + "" + name + ".jpg" );
                 string filePath = "/image/" + name + ".jpg" ;
                 MODEL.BusinessInfo mo = new MODEL.BusinessInfo();
                 //mo.Title = title;
                // mo.Contents = contect;
                 //mo.Fileds = filePath;
  
                 BLL.BusinessInfo bll = new BLL.BusinessInfo();
                 bll.Add(mo);
                 if (flag == true )
                 {
                     return "成功" ;
                 }
                 else
                 {
                     return "失败" ;
                 }
  
             }
             catch (Exception ex)
             {
                 mess = ex.Message;
             }
             if (mess != "" )
             {
                 return mess;
             }
             else
             {
                 return "文件上传成功" ;
             }
         }
         protected System.Drawing.Image Base64StringToImage(string strbase64)
         {
             try
             {
                 byte [] arr = Convert.FromBase64String(strbase64);
                 MemoryStream ms = new MemoryStream(arr);
                 //Bitmap bmp = new Bitmap(ms);
  
                 ms.Write(arr, 0 , arr.Length);
                 System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
                 ms.Close();
                 return image;
                 //return bmp;
             }
             catch (Exception ex)
             {
                 throw ex;
             }
         }
         /// <summary> 
         /// 把经过base64编码的字符串保存为文件 
         /// </summary> 
         /// <param name="base64String">经base64加码后的字符串 </param> 
         /// <param name="fileName">保存文件的路径和文件名 </param> 
         /// <returns>保存文件是否成功 </returns> 
         public static bool StringToFile(string base64String, string fileName)
         {
             //string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + @"/beapp/" + fileName; 
  
             System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
             System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
             if (!string.IsNullOrEmpty(base64String) && File.Exists(fileName))
             {
                 bw.Write(Convert.FromBase64String(base64String));
             }
             bw.Close();
             fs.Close();
             return true ;
         }
 
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值