8-11

来源:互联网 发布:java企业级项目开发 编辑:程序博客网 时间:2024/05/01 16:16
//服务器
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Drawing;using System.Web.Services;using System.IO;using System.Runtime.Serialization.Formatters.Binary;using System.Text;namespace WebService1{    /// <summary>    /// Summary description for Service1    /// </summary>    [WebService(Namespace = "http://tempuri.org/")]    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]    [System.ComponentModel.ToolboxItem(false)]    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.     // [System.Web.Script.Services.ScriptService]    public class Service1 : System.Web.Services.WebService    {         /*        [WebMethod]        public string  PutImage1()        {                       FileStream fin = new FileStream("C:\\Users\\samsung\\Desktop\\filename.txt", FileMode.Open, FileAccess.Read);            StreamReader brin = new StreamReader(fin, Encoding.Default);            string s = brin.ReadToEnd(); brin.Close();            Console.WriteLine(s);            byte[] ImgIn = Convert.FromBase64String(s);            System.IO.MemoryStream ms =               new System.IO.MemoryStream(ImgIn);            System.Drawing.Bitmap b =              (System.Drawing.Bitmap)Image.FromStream(ms);            b.Save("E:\\yu\\WebService1\\WebService1\\images\\1.png",                   System.Drawing.Imaging.ImageFormat.Png);            return s;                           }         */        [WebMethod(Description = "上传图片")]        public bool PutImage(string filename, string image)        {            //Bitmap small;            byte[] ImgIn = Convert.FromBase64String(image);            System.IO.MemoryStream ms =               new System.IO.MemoryStream(ImgIn);            System.Drawing.Bitmap b =              (System.Drawing.Bitmap)Image.FromStream(ms);            b.Save("E:\\project\\Linweijia\\ImagesUp\\" + filename,                   System.Drawing.Imaging.ImageFormat.Png);            //small = new System.Drawing.Bitmap("E:\\project\\Linweijia\\ImagesUp\\" + filename+".Png");              return true;        }        [WebMethod(Description = "下载图片")]        public string GetImage()        {            MemoryStream m = new System.IO.MemoryStream();            Bitmap bp = new System.Drawing.Bitmap("E:\\project\\Linweijia\\ImagesUp\\Hi.jpg");            bp.Save(m, System.Drawing.Imaging.ImageFormat.Png);            byte[] b = m.GetBuffer();            string base64string = Convert.ToBase64String(b);            return base64string;        }        [WebMethod(Description = "缩略图")]        private void SmallPic(string strOldPic, string strNewPic, int intWidth, int intHeight)         {             System.Drawing.Bitmap objPic, objNewPic;            try             {                 objPic = new System.Drawing.Bitmap(strOldPic);                objNewPic = new System.Drawing.Bitmap(objPic, intWidth, intHeight);                 objNewPic.Save(strNewPic);             }             catch                 (Exception exp)             {                 throw exp;                       }             finally             {                 objPic = null;                 objNewPic = null;            }        }    }}

 

GalleryAdapter.java

package com.example.test;import java.io.File;import java.io.FileFilter;import java.util.HashMap;import java.util.Vector; import android.content.Context;import android.content.res.TypedArray;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Environment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.CheckBox;import android.widget.CompoundButton;import android.widget.TextView;import android.widget.Toast;import android.widget.Gallery;import android.widget.ImageView;//public class GalleryAdapter extends BaseAdapterpublic class GalleryAdapter extends BaseAdapter {private Context mContext;private int mCount;private LayoutInflater mInflater;private int mGalleryItemBackground;private HashMap<Integer,View> hm;public static MyFile myPics;private int pic_num;private TextView tt;public GalleryAdapter(Context c, TextView t2){mContext = c;mInflater = LayoutInflater.from(c);myPics = new MyFile();pic_num = myPics.pic_num;mCount = pic_num;hm = new HashMap<Integer,View>(mCount);tt = t2;}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn myPics.paths.length;}@Overridepublic Object getItem(int arg0) {// TODO Auto-generated method stubreturn arg0;}@Overridepublic long getItemId(int arg0) {// TODO Auto-generated method stubreturn arg0;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {// TODO Auto-generated method stubView i;ImageView imageView = null;//TextView textView = null;CheckBox cb = null;i = hm.get(position);if (i==null){i = mInflater.inflate(R.layout.gallery_item, null);imageView = (ImageView) i.findViewById(R.id.item_gallery_image);cb = (CheckBox) i.findViewById(R.id.item_gallery_checkbox);imageView.setImageBitmap(str2bitmap(myPics.paths[position%myPics.paths.length],50,50));imageView.setAdjustViewBounds(true);cb.setOnCheckedChangeListener(new myCheckChangeListener(position));hm.put(position, i);}return i;}public class myCheckChangeListener implements CheckBox.OnCheckedChangeListener{    private int mPosition;public myCheckChangeListener(int position) {// TODO Auto-generated constructor stubmPosition = position;}@Overridepublic void onCheckedChanged(CompoundButton arg0, boolean isChecked) {// TODO Auto-generated method stubif (isChecked){myPics.select[mPosition] = true;//Toast.makeText(getBaseContext(), "你选择了第 "+Integer.toString(1+mPosition)+"张", Toast.LENGTH_SHORT).show();  }else{myPics.select[mPosition] = false;//Toast.makeText(getBaseContext(), "你取消选择了第 "+Integer.toString(1+mPosition)+"张", Toast.LENGTH_SHORT).show(); }int cnt=0;for (int i=0; i<pic_num; i++){if (myPics.select[i])cnt++;}tt.setText(Integer.toString(cnt));}        }public static Bitmap str2bitmap(String path, int height, int width){Bitmap b = null; BitmapFactory.Options options = new BitmapFactory.Options();   options.inJustDecodeBounds = true; b = BitmapFactory.decodeFile(path, options);   options.inJustDecodeBounds = false;   int h = options.outHeight; int w = options.outWidth; int beWidth = w/width; int beHeight = h/height; int be = 1; if (beWidth < beHeight){ be = beWidth; } else { be = beHeight; } if (be <= 0) be = 1; options.inSampleSize = be; b = BitmapFactory.decodeFile(path, options); return b;}public static Bitmap str2bitmap(String path){Bitmap b = null;BitmapFactory.Options options = new BitmapFactory.Options();  options.inJustDecodeBounds = false; b = BitmapFactory.decodeFile(path, options);  return b;}}

MainActivity.java

package com.example.test;import java.io.BufferedWriter;  import java.io.ByteArrayOutputStream;  import java.io.File;  import java.io.FileInputStream;  import java.io.FileOutputStream;  import java.io.FileWriter;  import java.io.IOException;  import java.util.HashMap;  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.graphics.Bitmap;    import android.graphics.BitmapFactory;    import android.graphics.drawable.BitmapDrawable;    import android.graphics.drawable.Drawable;    import android.os.Bundle;    import android.util.Log;    import android.view.View;    import android.view.View.OnClickListener;    import android.view.animation.AnimationUtils;    import android.widget.AdapterView;    import android.widget.AdapterView.OnItemSelectedListener;import android.widget.Button;    import android.widget.Gallery;    import android.widget.ImageSwitcher;    import android.widget.ImageView;    import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast;    import android.widget.AdapterView.OnItemClickListener;         public class MainActivity extends Activity //implements OnItemSelectedListener   {        Button bt;    //    Button down;       static public TextView t2;    private ImageSwitcher is;    private boolean isExist[];    private ProgressBar pb_upload;   // private static final String NAMESPACE = "http://tempuri.org/";         // private static String URL = "http://localhost:20383/Service1.asmx";     // private static final String METHOD_NAME = "PutImage";     // private static String SOAP_ACTION = "http://tempuri.org/PutImage";                 @Override        public void onCreate(Bundle savedInstanceState)        {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    isExist = null;        t2 = (TextView)findViewById(R.id.t2);    pb_upload = (ProgressBar)findViewById(R.id.progress_upload);    bt = (Button)findViewById(R.id.button1);            bt.setOnClickListener(new OnClickListener(){        @Override        public void onClick(View arg0) {        // TODO Auto-generated method stub    MyFile a= GalleryAdapter.myPics;    if (isExist==null)    isExist = new boolean[a.pic_num];    for (int k=0; k<isExist.length; k++)    isExist[k]=false;    a.setChoosePicNum();    pb_upload.setProgress(0);        new Thread(){       @Override     public void run() {       MyFile a= GalleryAdapter.myPics;    int p_all = a.choose_pic_num;    int cnt=0;    for(int k=0; k<a.pic_num; k++){        if (a.select[k])    cnt++;    pb_upload.setProgress((int)((double)cnt/p_all*100));        if(a.select[k] && !isExist[k]){    testUpload(a.paths[k]);      isExist[k]=true;    }        }        }       }.start();     //    Toast.makeText(MainActivity.this, "上传成功",//Toast.LENGTH_SHORT).show();    }         });           //获得ImageSwitcher对象             is = (ImageSwitcher) findViewById(R.id.Switcher);                      is.setFactory(new SwitcherFactory(MainActivity.this));//设置工厂,用来显示视图。             is.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in)); //设置切入动画 android.R.anim.slide_in_left             is.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));//设置切出动画 android.R.anim.slide_out_right                       //获得Gallery对象             final Gallery g = (Gallery) findViewById(R.id.Gallery);           //添加ImageAdapter给Gallery对象             g.setAdapter(new GalleryAdapter(this,t2));           //设置Gallery的事件监听             g.setOnItemClickListener(new OnItemClickListener() {               public void onItemClick(AdapterView<?> parent, View v, int position, long id)               {                  //设置ImageSwitcher图片来源                 //   String imagePath = ((ImageView)v).getContentDescription().toString();               //   Drawable bd = new BitmapDrawable(GalleryAdapter.str2bitmap(imagePath));//ImageSwitcher图片像素缩小为原来的1/4                 //   is.setImageDrawable(bd);               //    Toast.makeText(MainActivity.this,"你选择了"+(position+1)+" 号图片",Toast.LENGTH_SHORT).show();                          BitmapDrawable bd = new BitmapDrawable(GalleryAdapter.str2bitmap(GalleryAdapter.myPics.paths[position%GalleryAdapter.myPics.pic_num],300,100));           is.setImageDrawable(bd);           }           }); //       g.setOnItemSelectedListener(this);       g.setSelection(0);       BitmapDrawable bd = new BitmapDrawable(GalleryAdapter.str2bitmap(GalleryAdapter.myPics.paths[0],300,100));   is.setImageDrawable(bd);    }                 //   public void testUpload(){     public void testUpload(String path){         try{                // String srcUrl = "/mnt/sdcard/"; //路径                   //String fileName = "0.jpg";  //文件名                 //  FileInputStream fis = new FileInputStream(srcUrl + fileName);         String fileName = path.substring(path.lastIndexOf('/')+1,path.length());        FileInputStream fis = new FileInputStream(path);              ByteArrayOutputStream baos = new ByteArrayOutputStream();                 byte[] buffer = new byte[1024];                 int count = 0;                 while((count = fis.read(buffer)) >= 0){                     baos.write(buffer, 0, count);                 }                 String uploadBuffer = new String(Base64.encode(baos.toByteArray()));  //进行Base64编码                              String methodName = "PutImage";                 connectWebService(methodName,fileName, uploadBuffer);   //调用webservice                   System.out.println(uploadBuffer);               Log.i("connectWebService", "start");                 fis.close();             }catch(Exception e){                 e.printStackTrace();             }         }         public void testDownload(){             String srcUrl = "/sdcard/"; //路径               String methodName = "GetImage";            String ImageBase64 = downWebService(methodName);          if(ImageBase64.equals("failed")) return;          else{              try {                  byte[] buffer = Base64.decode(ImageBase64);                  FileOutputStream writer = new FileOutputStream(new File("/sdcard/yu.png"));                   //byte[] decoderBytes = decoder.decodeBuffer(pictureBuffer.toString());                    writer.write(buffer);              } catch (IOException e) {                  // TODO Auto-generated catch block                   e.printStackTrace();              }                         }                }      private String downWebService(String methodName) {             String namespace = "http://tempuri.org/";  // 命名空间,即服务器端得接口,注:后缀没加 .wsdl,             String SOAP_ACTION = "http://tempuri.org/"+methodName;                                                                     //服务器端我是用x-fire实现webservice接口的             String url = "http://10.0.2.2:20383/Service1.asmx";   //对应的url              //以下就是 调用过程了,不明白的话 请看相关webservice文档                  SoapObject soapObject = new SoapObject(namespace, methodName);                // soapObject.addProperty("filename", fileName);  //参数1   图片名              // soapObject.addProperty("image", imageBuffer);   //参数2  图片字符串               SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(                     SoapEnvelope.VER11);             HttpTransportSE httpTranstation = new HttpTransportSE(url);             envelope.dotNet = true;             envelope.bodyOut = soapObject;          envelope.setOutputSoapObject(soapObject);                      try {                 httpTranstation.call(SOAP_ACTION, envelope);                 Object result = envelope.getResponse();                 Log.i("connectWebService", result.toString());                 return result.toString();             } catch (Exception e) {                 e.printStackTrace();             }             return "failed";       }     //使用 ksoap2 调用webservice            private boolean connectWebService(String methodName,String fileName, String imageBuffer) {             String namespace = "http://tempuri.org/";  // 命名空间,即服务器端得接口,注:后缀没加 .wsdl,             String SOAP_ACTION = "http://tempuri.org/"+methodName;                                                                     //服务器端我是用x-fire实现webservice接口的             String url = "http://10.0.2.2:20383/Service1.asmx";   //对应的url              //以下就是 调用过程了,不明白的话 请看相关webservice文档                  SoapObject soapObject = new SoapObject(namespace, methodName);                 soapObject.addProperty("filename", fileName);  //参数1   图片名               soapObject.addProperty("image", imageBuffer);   //参数2  图片字符串               SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(                     SoapEnvelope.VER11);             HttpTransportSE httpTranstation = new HttpTransportSE(url);             envelope.dotNet = true;             envelope.bodyOut = soapObject;          envelope.setOutputSoapObject(soapObject);                      try {                 httpTranstation.call(SOAP_ACTION, envelope);                 Object result = envelope.getResponse();                 Log.i("connectWebService", result.toString());             } catch (Exception e) {                 e.printStackTrace();             }             return false;         }/*    //onItemSelectedListener    private int currentPos = -1;    private HashMap<Integer,BitmapDrawable> hmbd = new HashMap<Integer,BitmapDrawable>(GalleryAdapter.myPics.pic_num);@Overridepublic void onItemSelected(AdapterView<?> arg0, View arg1, int position,long arg3) {// TODO Auto-generated method stubif (currentPos != position){BitmapDrawable bd;bd = hmbd.get(position);if (bd == null){bd = new BitmapDrawable(GalleryAdapter.str2bitmap(GalleryAdapter.myPics.paths[position%GalleryAdapter.myPics.paths.length],300,100));hmbd.put(position, bd);}is.setImageDrawable(bd);currentPos = position;}}            @Overridepublic void onNothingSelected(AdapterView<?> arg0) {// TODO Auto-generated method stub}  */}    


MyFile.java

package com.example.test;import java.io.File;import java.util.ArrayList;import java.util.List;import android.os.Environment;public class MyFile {public String[] paths={"/mnt/sdcard/1.jpg"};private List<String> imagePathList;public int pic_num;public boolean select[];public int choose_pic_num;public MyFile(){imagePathList=getImagePathFromSD();        paths = imagePathList.toArray(new String[imagePathList.size()]);        pic_num = paths.length;        select = new boolean[pic_num];        for (int i=0; i<pic_num; i++)        select[i] = false;}public List<String> getImagePathFromSD(){List<String> it = new ArrayList<String>();String imagePath = Environment.getExternalStorageDirectory().toString();File mFile = new File(imagePath);File[] files = mFile.listFiles();for (int i=0; i<files.length; i++){File file = files[i];if (checkIsImageFile(file.getPath()))it.add(file.getPath());}return it;}public boolean checkIsImageFile(String fName){boolean isImageFormat;String end = fName.substring(fName.lastIndexOf(".")+1,fName.length()).toLowerCase();if (end.equals("jpg") || end.equals("gif") || end.equals("png")  || end.equals("jpeg") || end.equals("bmp")) {isImageFormat = true;} elseisImageFormat = false;return isImageFormat;}public void setChoosePicNum(){choose_pic_num=0;for (int i=0; i<pic_num; i++){if (select[i])choose_pic_num++;}}}

SwitcherFactory.java

package com.example.test;import android.content.Context;import android.view.View;import android.widget.ImageView;import android.widget.ViewSwitcher.ViewFactory; //实现并设置工厂内部接口的makeView方法,用来显示视图。public class SwitcherFactory implements ViewFactory {    // 上下文对象    private Context mContext;     public SwitcherFactory(Context context) {       super();       mContext = context;    }    @Override    public View makeView() {       ImageView iv = new ImageView(mContext);       iv.setScaleType(ImageView.ScaleType.FIT_CENTER);       return iv;    }}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/LinearLayout1"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <LinearLayout        android:id="@+id/info"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center" >        <LinearLayout            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="5dp"            android:layout_marginRight="5dp" >            <TextView                android:id="@+id/textView1"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="名称:"                android:textSize="20dp" />            <TextView                android:id="@+id/textView3"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="XX" />        </LinearLayout>        <LinearLayout            android:layout_width="wrap_content"            android:layout_height="match_parent"            android:layout_marginLeft="5dp"            android:layout_marginRight="5dp" >            <TextView                android:id="@+id/textView2"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="创建人:"                android:textSize="20dp" />            <TextView                android:id="@+id/textView4"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="XX" />        </LinearLayout>        <LinearLayout            android:layout_width="wrap_content"            android:layout_height="match_parent"            android:layout_marginLeft="5dp"            android:layout_marginRight="5dp" >            <TextView                android:id="@+id/textView5"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_gravity="bottom"                android:text="time" />        </LinearLayout>    </LinearLayout>    <TextView        android:id="@+id/line"        android:layout_width="fill_parent"        android:layout_height="0.2dp"        android:background="@color/green" />    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="vertical" >        <ImageSwitcher            android:id="@+id/Switcher"            android:layout_marginTop="5dp"android:scaleType="fitCenter"            android:layout_width="fill_parent"            android:layout_height="200dp" >        </ImageSwitcher>    </LinearLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="10dp"        android:orientation="vertical" >        <Gallery            android:id="@+id/Gallery"            android:layout_width="match_parent"            android:layout_height="70dp"            android:scaleType="fitCenter"            android:layout_marginLeft="5dp"            android:layout_marginRight="5dp"            android:layout_weight="1"             android:spacing = "10dp"/>    </LinearLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="10dp"        >           <TextView            android:id="@+id/t1"            android:layout_width="wrap_content"            android:layout_height="wrap_content"                        android:layout_marginLeft="20dp"            android:text="已选择:"             android:textSize="25dp"/>                <TextView            android:id="@+id/t2"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="25dp"            android:text="0" />                <Button            android:id="@+id/button1"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="100dp"            android:text="上 传"            android:textSize="25dp" />    </LinearLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginRight="40dp"    android:layout_marginLeft="40dp"        android:layout_marginTop="10dp" >        <ProgressBar            android:id="@+id/progress_upload"            style="?android:attr/progressBarStyleHorizontal"            android:layout_width="match_parent"            android:layout_height="50dp"            android:max="100"            android:progress="0" />    </LinearLayout></LinearLayout>


gallery_item.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/RelativeLayout1"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <ImageView        android:id="@+id/item_gallery_image"        android:layout_width="102dp"        android:layout_height="102dp"        android:scaleType="fitCenter"        android:src="@drawable/ic_launcher" />    <CheckBox        android:id="@+id/item_gallery_checkbox"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:text="" /></RelativeLayout>        

image_box.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/RelativeLayout1"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <ImageView        android:id="@+id/imageView1"        android:layout_width="102dp"        android:layout_height="102dp"        android:src="@drawable/ic_launcher" />    <CheckBox        android:id="@+id/checkBox1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:text="" /></RelativeLayout>





 

0 0
原创粉丝点击