Android調用拍照和本地相冊並上傳給服務器

package com.example.yaoc.myapplication;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;


import com.alibaba.fastjson.JSON;
import com.example.yaoc.myapplication.util.HttpUtil;
import com.example.yaoc.myapplication.util.LoginUserCache;
import com.example.yaoc.myapplication.util.Until;
import com.google.gson.Gson;


import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;


import org.json.JSONException;
import org.json.JSONObject;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2016/3/2.
 */
public class UpLoadImageActivity extends Activity implements View.OnClickListener {


    private static final int SELECT_PICTURE = 1;
    private static final int SELECT_CAMER = 2;


    List<String> pathStr;
    Context mContext;


    String path = "";


    ImageView ivDelete;
    MyAdapter ImgAdapter;
    //TODO 根據這個變量來判斷是否顯示刪除圖標,true是顯示,false是不顯示
    private boolean isShowDelete = false;
    List<Bitmap> imgList = new ArrayList<Bitmap>();


    //TODO 上傳圖片的Button
    private Button add_image, btn_image, back_activity;


    private GridView gv;
    Bundle bundlefid;
    String fid;
    String code;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.uploadimage_activity);

//賬戶登陸後的用戶code

        code = LoginUserCache.GetUserCode(this);




        initUI();


//賬戶登陸後前一頁傳來的用戶id

        bundlefid = getIntent().getBundleExtra("fid");
        fid = bundlefid.getString("fid");




    }


    private void initUI() {


        gv = (GridView) findViewById(R.id.gv_img);
        btn_image = (Button) findViewById(R.id.btn_image);
        back_activity = (Button) findViewById(R.id.back_activity);


        back_activity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Intent intent = new Intent(UpLoadImageActivity.this, ListActivity.class);
                startActivity(intent);
                finish();
            }
        });




        /**
         * 圖片的控件
         */


        pathStr = new ArrayList<String>();


        mContext = this;
        ivDelete = (ImageView) findViewById(R.id.img_delete);
        add_image = (Button) findViewById(R.id.add_image);


        add_image.setOnClickListener(this);


        gv = (GridView) this.findViewById(R.id.gv_img);
        ImgAdapter = new MyAdapter();
        ImgAdapter.setIsShowDelete(isShowDelete);
        gv.setAdapter(ImgAdapter);
        /**
         * GridView的單擊事件
         */
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {


            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ivDelete = (ImageView) findViewById(R.id.img_delete);
                if (isShowDelete == true) {
                    //TODO 如果處於正在刪除的狀態,單擊則刪除圖標消失
                    isShowDelete = false;
                    ImgAdapter.setIsShowDelete(isShowDelete);
                } else {
                    //TODO  處於正常狀態
                    if (position > imgList.size() - 1) {
                        //TODO  添加圖片
                        selectimg();
                    } else {
                        //TODO  跳轉,可以做放大使用,自己添加吧。
                        Toast.makeText(UpLoadImageActivity.this, "長按圖片進入刪除狀態...",
                                Toast.LENGTH_SHORT).show();
                    }
                }


                ImgAdapter.notifyDataSetChanged();
            }
        });


        /**
         * GridView長按事件
         */
        gv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {


            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //TODO  長按顯示刪除圖標
                if (isShowDelete == false) {
                    isShowDelete = true;
                }
                ImgAdapter.setIsShowDelete(isShowDelete);


                return true;
            }
        });




    }


    /**
     * 選擇圖片來源
     */
    private void selectimg() {
        final CharSequence[] items = {"拍照上傳", "從相冊選擇"};
        new AlertDialog.Builder(this).setTitle("選擇圖片來源")
                .setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == SELECT_PICTURE) {
                            toGetLocalImage();
                        } else {
                            toGetCameraImage();
                        }
                    }
                }).create().show();
    }




    /**
     * 調用圖片上傳的接口
     */
    private void uploadRepairRecordImageForAndroid() {


//        Toast.makeText(this, "開始上傳圖片...", Toast.LENGTH_SHORT).show();


        FinalHttp http = new FinalHttp();
        final AjaxParams params = new AjaxParams();


        for (int i = 0; i < pathStr.size(); i++) {
            String paths = pathStr.get(i);


            file = new File(paths);


            try {
                params.put("url", HttpUtil.IMAGESAVE_PATH);//服務器端接受圖片的存放接口
                params.put("fid", fid);
                params.put("code", code);
                params.put("image" + 1, file);
                params.put("fileName", file.getName());


                Log.v("-------------", paths + "-------" + file.isFile() + "-------" + file.length());


            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }




            http.post(HttpUtil.UPLOAD_IMAGE, params, new AjaxCallBack<String>() {


                @Override
                public void onStart() {
                    super.onStart();
                    Toast.makeText(UpLoadImageActivity.this, "圖片上傳中...", Toast.LENGTH_LONG).show();
                }


                @Override
                public void onSuccess(String s) {
                    super.onSuccess(s);


                    /**
                     * 根據服務器返回的json數據,判斷上傳是否成功
                     */




                    if (s.equals("success")) {
                        Toast.makeText(UpLoadImageActivity.this, "恭喜您,圖片上傳成功...", Toast.LENGTH_LONG).show();
                        add_image.setVisibility(View.GONE);
                        btn_image.setVisibility(View.VISIBLE);
                    } else {
                        Toast.makeText(UpLoadImageActivity.this, "圖片上傳失敗,請重新上傳...", Toast.LENGTH_LONG).show();
                    }




                }


                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    Toast.makeText(UpLoadImageActivity.this, "圖片上傳失敗...", Toast.LENGTH_SHORT).show();
                }
            });




        }




    }




    /**
     * 用於gridview顯示多張照片
     *
     * @author wlc
     * @date 2015-4-16
     */
    public class MyAdapter extends BaseAdapter {


        private boolean isDelete; //TODO  用於刪除圖標的顯隱
        private LayoutInflater inflater = LayoutInflater.from(mContext);


        @Override
        public int getCount() {


            /**
             * 需要額外多出一個用於添加圖片,這裏限制上傳2張
             */
            return 2;


        }


        @Override
        public Object getItem(int arg0) {
            return imgList.get(arg0);
        }


        @Override
        public long getItemId(int arg0) {
            return arg0;
        }


        @Override
        public View getView(final int position, View convertView, ViewGroup arg2) {


            /**
             * 初始化頁面和相關控件
             */
            convertView = inflater.inflate(R.layout.item_imgview, null);
            ImageView img_pic = (ImageView) convertView
                    .findViewById(R.id.img_pic);
            LinearLayout ly = (LinearLayout) convertView
                    .findViewById(R.id.layout);
            LinearLayout ll_picparent = (LinearLayout) convertView
                    .findViewById(R.id.ll_picparent);
            ImageView delete = (ImageView) convertView
                    .findViewById(R.id.img_delete);


            /**
             * 默認的添加圖片的那個item是不需要顯示刪除圖片的
             */
            if (imgList.size() >= 1) {
                if (position <= imgList.size() - 1) {
                    ll_picparent.setVisibility(View.GONE);
                    img_pic.setVisibility(View.VISIBLE);
                    img_pic.setImageBitmap(imgList.get(position));
                    //TODO  設置刪除按鈕是否顯示
                    delete.setVisibility(isDelete ? View.VISIBLE : View.GONE);
                }
            }


            /**
             * 當處於刪除狀態時,刪除事件可用
             * 注意:必須放到getView這個方法中,放到onitemClick中是不起作用的
             */
            if (isDelete) {
                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {


                        imgList.remove(position);
                        ImgAdapter.notifyDataSetChanged();


                    }
                });
            }


            return convertView;
        }


        /**
         * 設置是否顯示刪除圖片
         *
         * @param isShowDelete
         */
        public void setIsShowDelete(boolean isShowDelete) {
            this.isDelete = isShowDelete;
            notifyDataSetChanged();
        }


    }




    /**
     * 選擇本地圖片
     */
    public void toGetLocalImage() {


        startActivityForResult(createDefaultOpenableIntent(), SELECT_PICTURE);


    }


    private Intent createDefaultOpenableIntent() {


        //選擇圖片 (android4.4以上版本此方法纔可獲得選擇的圖片,舊方法無效,低版本兼容此方法)
        Intent i = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        return i;
    }




    File out;


    /**
     * 照相選擇圖片
     */
    public void toGetCameraImage() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
        String photoname = "a.jpg";
        out = new File(getSDPath(), photoname);
        Uri uri = Uri.fromFile(out);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, SELECT_CAMER);
    }


    /**
     * 獲取sd卡路徑
     *
     * @return
     */
    private File getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); //TODO 判斷sd卡是否存在
        if (sdCardExist) {
            // 這裏可以修改爲你的路徑
            sdDir = new File(Environment.getExternalStorageDirectory()
                    + "/DCIM/Camera");


        }
        return sdDir;
    }




    File file;


    @Override
    public void onClick(View v) {


        switch (v.getId()) {
            case R.id.add_image:


                if (pathStr.size() == 0) {
                    Toast.makeText(this, "請先拍照再上傳...", Toast.LENGTH_LONG).show();
                } else {
                    uploadRepairRecordImageForAndroid();
                }


                break;


        }
    }




    int count = 1;


    /**
     * 回調
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                /**
                 * 從相冊選擇
                 */
                case SELECT_PICTURE:
                    Uri vUri = data.getData();
                    //TODO  將圖片內容解析成字節數組
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = managedQuery(vUri, proj, null, null, null);
                    System.out.print("cursor" + cursor);


                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    System.out.print("column_index" + column_index);


                    cursor.moveToFirst();
                    String path1 = cursor.getString(column_index);
                    Bitmap bm = Until.getxtsldraw(mContext, path1);




                    count++;
                    path = Until.creatfile(mContext, bm, "userImageName" + count);


                    pathStr.add(path);


                    Log.v("+++++++" + path, path);


                    if (null != bm && !"".equals(bm)) {
                        imgList.add(bm);
                    }
                    ImgAdapter.notifyDataSetChanged();
                    break;
                /**
                 * 拍照添加圖片
                 */
                case SELECT_CAMER:


                    Bitmap bm1 = Until.getxtsldraw(mContext, out.getAbsolutePath());




                    count++;
                    path = Until.creatfile(mContext, bm1, "userImageName" + count);


                    pathStr.add(path);


                    Log.v("-------------路徑", path);


                    if (null != bm1 && !"".equals(bm1)) {
                        imgList.add(bm1);
                    }
                    ImgAdapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }


        }


    }




}



<--------------------------------------uploadimage_activity.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="match_parent"
    android:layout_gravity="center"
    android:orientation="vertical">




    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:text="請您選擇是否上傳故障圖片...."
        android:textColor="#EE2C2C"
        android:textSize="30sp" />


    <GridView
        android:id="@+id/gv_img"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:horizontalSpacing="7dp"
        android:listSelector="@null"
        android:numColumns="3"
        android:paddingTop="40dp"
        android:scrollbars="none"
        android:stretchMode="columnWidth"
        android:verticalSpacing="7dp" />


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:orientation="horizontal">




        <Button
            android:id="@+id/add_image"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:background="@drawable/shapes"
            android:gravity="center"
            android:text="上傳" />
        <Button
            android:id="@+id/btn_image"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:gravity="center"
            android:background="@drawable/shape"
            android:visibility="gone"
            android:text="上傳" />


        <Button
            android:id="@+id/back_activity"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:background="@drawable/shape"
            android:text="返回"
            android:textSize="@dimen/text_size" />


    </LinearLayout>


</LinearLayout>




<------------------------item_imgview.xml>


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical">


    <FrameLayout
        android:layout_width="80dp"
        android:layout_height="80dp">


        <!-- 添加圖片,覆蓋下面圖片的大小 -->


        <ImageView
            android:id="@+id/img_pic"
            android:layout_width="180dp"
            android:layout_height="180dp"
            android:layout_gravity="center"
            android:src="@drawable/add_icon"
            android:visibility="gone" />


        <LinearLayout
            android:id="@+id/ll_picparent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center"
            android:background="@drawable/image_style"
            android:gravity="center"
            android:orientation="vertical">


            <!-- 添加的圖片 -->


            <ImageView
                android:layout_width="56dp"
                android:layout_height="56dp"
                android:src="@drawable/add_icon" />
            <!-- 添加的說明 -->


            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="故障圖片"
                android:textColor="#b3b3b3" />
        </LinearLayout>


        <!-- 刪除的圖片 -->


        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">


            <ImageView
                android:id="@+id/img_delete"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:background="@drawable/img_delet"
                android:visibility="gone" />
        </RelativeLayout>
    </FrameLayout>


</LinearLayout>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章