Android实现拍照选择相册图片上传图片(多图片上传)功能

安卓多图片上传代码

直接上代码

1.主程序入口XML文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zanelove.photoapp" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name="com.zanelove.photoapp.MyPhotoApp_Data_Application"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="com.zanelove.photoapp.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".UploadImage_Activity"/>
    </application>

</manifest>

2.主程序入口代码(MainActivity)

package com.zanelove.photoapp;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.*;
import com.zanelove.photoapp.utils.FileUtil;
import com.zanelove.photoapp.utils.File_Tool;
import com.zanelove.photoapp.utils.HttpUtil;
import com.zanelove.photoapp.utils.SelectPhotoUtil;
import com.zanelove.photoapp.view.Pop_Viewpager_Item_Pz;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.*;
import java.net.ConnectException;
import java.util.ArrayList;

public class MainActivity extends Activity implements View.OnClickListener {
    private int is_img = 0;
    private String oncline_image_tag;
    private Pop_Viewpager_Item_Pz isn;
    private LinearLayout viewpager_item_zp_ll;
    private Toast toast;
    private ArrayList<String> lists = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        File_Tool.createDIRFrom("");
        File_Tool.createDIRFrom("photo");
        File_Tool.createDIRFrom("photo/image");

        toast = Toast.makeText(this,"",Toast.LENGTH_SHORT);
        init();
    }

    private void init() {

        initPermission();
        viewpager_item_zp_ll = (LinearLayout) this.findViewById(R.id.viewpager_item_zp_ll);

        ImageView viewpager_item_xj = (ImageView) this.findViewById(R.id.viewpager_item_xj);
        viewpager_item_xj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
            if (viewpager_item_zp_ll.getVisibility() == View.VISIBLE) {
                viewpager_item_zp_ll.setVisibility(View.GONE);
            } else {
                viewpager_item_zp_ll.setVisibility(View.VISIBLE);
            }
            }
        });

        ImageView pz1 = (ImageView) this.findViewById(R.id.viewpager_item_zp_1);
        pz1.setTag("pz1");
        pz1.setOnClickListener(this);

        ImageView pz2 = (ImageView) this.findViewById(R.id.viewpager_item_zp_2);
        pz2.setTag("pz2");
        pz2.setOnClickListener(this);

        ImageView pz3 = (ImageView) this.findViewById(R.id.viewpager_item_zp_3);
        pz3.setTag("pz3");
        pz3.setOnClickListener(this);

        ImageView pz4 = (ImageView) this.findViewById(R.id.viewpager_item_zp_4);
        pz4.setTag("pz4");
        pz4.setOnClickListener(this);

        TextView next_tv = (TextView) this.findViewById(R.id.viewpager_item_next);
        next_tv.setText("提交");
        next_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Put_UserAnser_Task().execute();
            }
        });

        isn = new Pop_Viewpager_Item_Pz(this);
    }

    private static final int CAMERA_WITH_DATA = 1001;
    private static final int PHOTO_PICKED_WITH_DATA = 1002;

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case PHOTO_PICKED_WITH_DATA: // 从本地选择图片
                Uri selectedImageUri = data.getData();
                if (selectedImageUri != null) {
                    this.setImageViewByTask(FileUtil.getPath(this, data.getData()));
                }
                break;

            case CAMERA_WITH_DATA: // 拍照
                SelectPhotoUtil.doPhoto(this);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    /**
     * 根据图片的绝对地址. 给指定Tag标签的图片赋值.
     *
     * @param img_path
     */
    public void setImageViewByTask(String img_path) {
        ImageView iv = (ImageView) viewpager_item_zp_ll.findViewWithTag(oncline_image_tag);

        String ys_path = ys_img(img_path);

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(ys_path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Bitmap bm = BitmapFactory.decodeStream(fis);
        iv.setImageBitmap(bm);

        /**
         * 设置下一个增加图片的按钮.
         */
        int i = Integer.parseInt(oncline_image_tag.substring(oncline_image_tag.length() - 1, oncline_image_tag.length()));
        String tags = oncline_image_tag.substring(0, oncline_image_tag.length() - 1);
        ImageView next_iv = (ImageView) viewpager_item_zp_ll.findViewWithTag(tags + (i + 1));
        if (i != 4) {
            if (i == 3) {
                next_iv = (ImageView) viewpager_item_zp_ll.findViewWithTag(tags + "4");
            } else {
                next_iv = (ImageView) viewpager_item_zp_ll.findViewWithTag(tags + (i + 1));
            }
            is_img++;
            next_iv.setVisibility(View.VISIBLE);
        }
        lists.add(img_path);
    }

    /**
     * 压缩图片.
     */
    private String ys_img(String img_path) {

        String[] path_arr = img_path.split("/");
        String[] name_arr = path_arr[path_arr.length - 1].split("\\.");
        String path = File_Tool.SDPATH + "image/" + name_arr[0] + ".png";

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高
        Bitmap bitmap = BitmapFactory.decodeFile(img_path, options); // 此时返回bm为空
        options.inJustDecodeBounds = false;
        // 计算缩放比
        int be = (int) (options.outHeight / 60);
        if (be <= 0)
            be = 1;
        options.inSampleSize = be;
        // 重新读入图片,注意这次要把options.inJustDecodeBounds 设为 false哦
        bitmap = BitmapFactory.decodeFile(img_path, options);
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        ImageView iv = new ImageView(this);
        iv.setImageBitmap(bitmap);
        //bitmap = compressImage(Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), false));
        // 这样我们就可以读取较大的图片而不会内存溢出了。如果你想把压缩后的图片保存在Sdcard上的话就很简单了:
        File file = new File(path);
        try {
            FileOutputStream out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.PNG, 50, out)) {
                out.flush();
                out.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * 提交用户文字答案接口数据.
     *
     * @author wanglei
     */
    class Put_UserAnser_Task extends AsyncTask<String, Integer, String> {
        ArrayList<String> id_list = new ArrayList<String>();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... arg0) {
            MyPhotoApp_Data_Application myphoto = (MyPhotoApp_Data_Application) getApplication();
            //TODO
            String url = myphoto.getUrl_host() + "port&a=userPaperAnswer" + "&sid=" + myphoto.getSessionid(), resurt = "";
            ArrayList<NameValuePair> val_list = new ArrayList<NameValuePair>();
            try {
                val_list.add(new BasicNameValuePair("is_img", is_img > 0 ? "1" : "0")); // $is_img=1有照片,
                resurt = HttpUtil.getData(MainActivity.this, url, val_list, HttpUtil.METHOD_POST);
            } catch (ConnectException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return resurt;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if ("1".equals(result)) {
                if (is_img > 0) {
                    int img_sum = 0;
                    Intent intent = new Intent(MainActivity.this, UploadImage_Activity.class);

                    for (int i=0;i<4;i++) {
                        img_sum++;
                        id_list.add(""+(i+1));
                    }
                    intent.putExtra("img_sum", img_sum);
                    intent.putStringArrayListExtra("id_list", id_list);
                    intent.putStringArrayListExtra("lists", lists);

                    MainActivity.this.startActivityForResult(intent, 101);
                    MainActivity.this.finish();
                } else {
                    toast.setText("提交成功");
                    toast.show();
                }
            } else {
                toast.setText("提交失败");
                toast.show();
            }
        }
    }

    @Override
    public void onClick(View v) {
        oncline_image_tag = v.getTag().toString();
        isn.show();
    }

    private void initPermission() {
        String permissions[] = {Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm :permissions){
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
                //进入到这里代表没有权限.

            }
        }
        String tmpList[] = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()){
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123);
        }

    }
}

3.主程序页面(activity_main.xml)XML文件

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="vertical"
            android:background="@color/color_white">

    <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="@dimen/size_50dp" >

        <TextView
                android:id="@+id/viewpager_item_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/size_14dp"
                android:padding="@dimen/size_14dp"
                android:textColor="@color/color_000"
                android:textSize="@dimen/size_14dp" />

        <RelativeLayout
                android:id="@+id/viewpager_item_viewed"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/viewpager_item_title"
                android:layout_marginLeft="@dimen/size_14dp"
                android:layout_marginRight="@dimen/size_14dp"
                android:background="@drawable/bg_ed_shape" >

            <EditText
                    android:id="@+id/viewpager_item_edittext"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@null"
                    android:gravity="top"
                    android:hint="@string/viewpager_edittext_hint"
                    android:inputType="textMultiLine"
                    android:maxLines="50"
                    android:minHeight="@dimen/size_150dp"
                    android:padding="@dimen/size_14dp"
                    android:textColor="@color/color_000"
                    android:textColorHint="@color/color_c"
                    android:textSize="@dimen/size_14dp" />

            <LinearLayout
                    android:id="@+id/viewpager_item_zp_ll"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_above="@+id/line"
                    android:orientation="horizontal"
                    android:padding="@dimen/size_10dp"
                    android:visibility="gone" >

                <ImageView
                        android:id="@+id/viewpager_item_zp_1"
                        android:layout_width="@dimen/size_40dp"
                        android:layout_height="@dimen/size_40dp"
                        android:background="@drawable/xk" />

                <ImageView
                        android:id="@+id/viewpager_item_zp_2"
                        android:layout_width="@dimen/size_40dp"
                        android:layout_height="@dimen/size_40dp"
                        android:layout_marginLeft="@dimen/size_10dp"
                        android:background="@drawable/xk"
                        android:visibility="gone" />

                <ImageView
                        android:id="@+id/viewpager_item_zp_3"
                        android:layout_width="@dimen/size_40dp"
                        android:layout_height="@dimen/size_40dp"
                        android:layout_marginLeft="@dimen/size_10dp"
                        android:background="@drawable/xk"
                        android:visibility="gone" />

                <ImageView
                        android:id="@+id/viewpager_item_zp_4"
                        android:layout_width="@dimen/size_40dp"
                        android:layout_height="@dimen/size_40dp"
                        android:layout_marginLeft="@dimen/size_10dp"
                        android:background="@drawable/xk"
                        android:visibility="gone" />
            </LinearLayout>

            <ImageView
                    android:id="@+id/line"
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:layout_below="@+id/viewpager_item_edittext"
                    android:background="@color/color_c9" />

            <RelativeLayout
                    android:id="@+id/viewpager_item_viewxj"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/viewpager_item_edittext"
                    android:layout_margin="1dp"
                    android:background="@color/color_bg_hui" >

                <ImageView
                        android:id="@+id/viewpager_item_xj"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="@dimen/size_13dp"
                        android:src="@drawable/xj" />
            </RelativeLayout>

            <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/viewpager_item_viewxj" />
        </RelativeLayout>

        <TextView
                android:id="@+id/viewpager_item_next"
                style="@style/bt_style_bgtowhite"
                android:layout_below="@+id/viewpager_item_viewed"
                android:layout_marginTop="@dimen/size_27dp" />
    </RelativeLayout>

</ScrollView>

4.上传图片代码(UploadImage_Activity)

package com.zanelove.photoapp;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.RemoteViews;
import android.widget.TextView;
import com.zanelove.photoapp.utils.File_Tool;
import com.zanelove.photoapp.view.CircleProgressBar;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 上传图片
 */
public class UploadImage_Activity extends Activity {

    private int len = 0;
    private NotificationManager manager;
    private Notification notif;
    private ArrayList<String> id_list;
    private TextView title_info;
    private CircleProgressBar circleProgressBar;
    private MyPhotoApp_Data_Application myapp;
    private ArrayList<String> lists;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.upload_image);
        myapp = (MyPhotoApp_Data_Application) getApplication();
        init_PutImg();
    }
    private void init_PutImg() {

        title_info = (TextView) findViewById(R.id.title_info);

        PendingIntent pIntent = PendingIntent.getActivity(UploadImage_Activity.this, 0, new Intent(), 0);
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notif = new Notification();
        notif.icon = R.drawable.ic_launcher;
        notif.tickerText = "正在上传作答文件";
        notif.flags = Notification.FLAG_AUTO_CANCEL;

        // 通知栏显示所用到的布局文件
        notif.contentView = new RemoteViews(getPackageName(), R.layout.content_view);
        notif.contentIntent = pIntent;
        manager.notify(0, notif);
        manager.cancel(0);

        circleProgressBar = (CircleProgressBar) findViewById(R.id.circleProgressbar);
        circleProgressBar.setProgress(0);

        new UploadImageThread().start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    notif.contentView.setTextViewText(R.id.content_view_text1, len + " %");
                    notif.contentView.setProgressBar(R.id.content_view_progress, 100, len, false);
                    manager.notify(0, notif);
                    circleProgressBar.setProgress(len);
                    break;
                case 1:
                    title_info.setText("作答上传完成");
                    manager.cancel(0);
                    break;
                default:
                    break;
            }
        }
    };

    private class UploadImageThread extends Thread {
        private Timer timer = new Timer();

        @Override
        public void run() {
            super.run();
            id_list = getIntent().getStringArrayListExtra("id_list");
            lists = getIntent().getStringArrayListExtra("lists");
            int img_sum = getIntent().getIntExtra("img_sum", 1), num = 0;
            int d = 100 / img_sum;

            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Message msg = new Message();
                    msg.what = 0;
                    msg.obj = len;
                    handler.sendMessage(msg);

                    if (len == 100) {
                        timer.cancel();
                        handler.sendEmptyMessage(1);
                    } else {
                        if (len < 95) {
                            len++;
                        }
                    }

                }
            }, 0, 1000);
            for (String img_path : lists) {
                int n = 0;
                for (String id : id_list) {
                    upload(img_path, "zanelove" + "_" + id + "_" + n);
                    n++;
                    num++;
                    len = num * d;
                }
            }

            len = 100;
        }
    }

    private void upload(String pathToOurFile, String name) {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        //TODO
        String urlServer = myapp.getUrl_host() + "port&a=uploadPic&id=" + name + "&ueid=" + "*" + "&tcid=" + "*" + "&sid=" + myapp.getSessionid();
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;

        try {

            FileInputStream fileInputStream = new FileInputStream(new File(upload_ys_img(pathToOurFile)));

            URL url = new URL(urlServer);
            connection = (HttpURLConnection) url.openConnection();

            // Allow Inputs &amp; Outputs.
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            connection.setRequestMethod("POST");

            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadfile\";filename=\"" + pathToOurFile + "\"" + lineEnd);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // Read file
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

			//取得Response内容
            InputStream is = connection.getInputStream();

            int ch;
            StringBuffer sbf = new StringBuffer();
            while ((ch = is.read()) != -1) {
                sbf.append((char) ch);
            }

            fileInputStream.close();
            outputStream.flush();
            outputStream.close();
        } catch (Exception ex) {
            // Exception handling
        }
    }

    /**
     * 压缩用于上传的图片
     */

    private String upload_ys_img(String img_path) {

        String[] path_arr = img_path.split("/");
        String[] name_arr = path_arr[path_arr.length - 1].split("\\.");
        String path = File_Tool.SDPATH + "image/" + name_arr[0] + ".png";

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高
        Bitmap bitmap = BitmapFactory.decodeFile(img_path, options); // 此时返回bm为空
        options.inJustDecodeBounds = false;
        // 计算缩放比
        int be = (int) (options.outHeight / 1280);
        if (be <= 0)
            be = 1;
        options.inSampleSize = be;
        // 重新读入图片,注意这次要把options.inJustDecodeBounds 设为 false哦
        bitmap = BitmapFactory.decodeFile(img_path, options);
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        bitmap = compressImage(Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), false));
        // 这样我们就可以读取较大的图片而不会内存溢出了。如果你想把压缩后的图片保存在Sdcard上的话就很简单了:
        File file = new File(path);
        try {
            FileOutputStream out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out)) {
                out.flush();
                out.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return path;
    }

    private Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100 && options > 30) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            options -= 10;// 每次都减少10
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
}

5.设置获取图片还是照片

package com.zanelove.photoapp.view;


import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import com.zanelove.photoapp.R;
import com.zanelove.photoapp.utils.SelectPhotoUtil;

/**
 *
 * 设置获取图片还是照片
 * Created by zanelove on 2019-5-5.
 *
 */
public class Pop_Viewpager_Item_Pz {

    private static final int CAMERA_WITH_DATA = 1001;
    private static final int PHOTO_PICKED_WITH_DATA = 1002;
    private Activity activity;
    private TextView viewpager_pop_pz_pz, viewpager_pop_pz_xc, viewpager_pop_pz_back;

    public Dialog mDialog;

    public Dialog getmDialog() {
        return mDialog;
    }

    public void setmDialog(Dialog mDialog) {
        this.mDialog = mDialog;
    }

    public Pop_Viewpager_Item_Pz(Activity context) {
        activity = context;
        mDialog = new Dialog(context, R.style.Setting_Question_Submit_Dialog_Style);

        mDialog.setContentView(R.layout.viewpager_item_pop_pz);
        Window window = mDialog.getWindow();
        WindowManager wm = context.getWindowManager();
        Display d = wm.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams p = window.getAttributes();
        p.width = (int) (d.getWidth() * 0.85);
        window.setAttributes(p);
        mDialog.setFeatureDrawableAlpha(Window.FEATURE_OPTIONS_PANEL, 0);
        window.setWindowAnimations(android.R.anim.fade_in);

        viewpager_pop_pz_pz = (TextView) mDialog.findViewById(R.id.viewpager_pop_pz_pz);
        viewpager_pop_pz_pz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                doTakePhoto();
            }
        });
        viewpager_pop_pz_xc = (TextView) mDialog.findViewById(R.id.viewpager_pop_pz_xc);
        viewpager_pop_pz_xc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                doSelectImageFromLoacal();
            }
        });

        viewpager_pop_pz_back = (TextView) mDialog.findViewById(R.id.viewpager_pop_pz_back);
        viewpager_pop_pz_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dismiss();
            }
        });
    }

    public void show() {
        mDialog.show();
    }

    public void dismiss() {
        mDialog.dismiss();
    }

    /**
     * 拍照获取图片
     */
    private void doTakePhoto() {
        SelectPhotoUtil.takePhoto(activity);
        mDialog.dismiss();
    }

    /**
     * 从本地手机中选择图片
     */
    private void doSelectImageFromLoacal() {
        Intent localIntent = new Intent();
        localIntent.setType("image/*");
        localIntent.setAction(Intent.ACTION_GET_CONTENT);
        localIntent.addCategory(Intent.CATEGORY_OPENABLE);
        Intent localIntent2 = Intent.createChooser(localIntent, "选择图片");
        activity.startActivityForResult(localIntent2, PHOTO_PICKED_WITH_DATA);

        mDialog.dismiss();
    }
}

6.使用照相机拍照获取图片

package com.zanelove.photoapp.utils;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;
import com.zanelove.photoapp.MainActivity;

/**
 * Created by zanelove on 2019-5-5.
 */
public class SelectPhotoUtil {
    /**
     * 使用照相机拍照获取图片
     */
    public static final int SELECT_PIC_BY_TACK_PHOTO = 1001;

    private static Uri photoUri;
    private static String picPath = null;

    /**
     * 拍照获取图片
     */
    public static void takePhoto(Activity activity) {

        String SDState = Environment.getExternalStorageState();
        if (SDState.equals(Environment.MEDIA_MOUNTED)) {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//"android.media.action.IMAGE_CAPTURE"

            ContentValues values = new ContentValues();
            photoUri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

            activity.startActivityForResult(intent, SELECT_PIC_BY_TACK_PHOTO);
        } else {
            Toast.makeText(activity, "内存卡不存在", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 选择图片后,获取图片的路径
     * @param activity
     */
    public static void doPhoto(Activity activity) {

        String[] pojo = {MediaStore.Images.Media.DATA};
        Cursor cursor = activity.managedQuery(photoUri, pojo, null, null, null);
        if (cursor != null) {
            int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
            cursor.moveToFirst();
            picPath = cursor.getString(columnIndex);
            try {
                //4.0以上的版本会自动关闭 (4.0--14; ; 4.0.3--15)
                if (Integer.parseInt(Build.VERSION.SDK) < 14) {
                    cursor.close();
                }
            } catch (Exception e) {
            }
        }
        if (picPath != null && (picPath.endsWith(".png") || picPath.endsWith(".PNG") || picPath.endsWith(".jpg") || picPath.endsWith(".JPG"))) {
            if(activity instanceof MainActivity) {
                ((MainActivity)activity).setImageViewByTask(picPath);
            }
        } else {
            Toast.makeText(activity, "选择图片文件不正确", Toast.LENGTH_LONG).show();
        }
    }
}

7.监听上传进度页面(content_view.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="@dimen/size_10dp"
        android:layout_marginRight="@dimen/size_10dp"
        android:background="@drawable/ic_launcher" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="@dimen/size_10dp"
        android:layout_toRightOf="@+id/icon" >

        <TextView
            android:id="@+id/content_view_text1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="@dimen/size_8dp"
            android:text="0 %"
            android:textColor="@color/color_c50619"
            android:textSize="@dimen/size_14dp" />

        <ProgressBar
            android:id="@+id/content_view_progress"
            style="@android:style/Widget.ProgressBar.Horizontal"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:layout_below="@+id/content_view_text1"
            android:layout_marginTop="14dp"
            android:max="100"
            android:progressDrawable="@drawable/barcolor" />
    </RelativeLayout>

</RelativeLayout>

8.上传进度条展示页面(upload_image.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/color_bg_hui" >

    <include
            android:id="@+id/yuan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            layout="@layout/my_circle_progressbar_relativelayout" />

    <TextView
            android:id="@+id/title_info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/yuan"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="@dimen/size_25dp"
            android:text="@string/upload_image_text"
            android:textColor="@color/color_666"
            android:textSize="@dimen/size_16dp" />

</RelativeLayout>

10.选择拍照和选取图片UI页面(viewpager_item_pop_pz.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

    <ImageView
            android:id="@+id/viewpager_pop_pz_iv"
            android:layout_width="match_parent"
            android:layout_height="@dimen/size_20dp"
            android:layout_alignParentBottom="true" />

    <TextView
            android:id="@+id/viewpager_pop_pz_back"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/viewpager_pop_pz_iv"
            android:layout_marginTop="@dimen/size_12dp"
            android:background="@drawable/viewpager_pop_pz_shape"
            android:clickable="true"
            android:gravity="center"
            android:padding="@dimen/size_12dp"
            android:text="取消"
            android:textColor="@drawable/bt_bg_selector_bgtofc4025_tv"
            android:textSize="@dimen/size_20dp" />

    <RelativeLayout
            android:id="@+id/viewpager_pop_pz"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/viewpager_pop_pz_back"
            android:background="@drawable/viewpager_pop_pz_shape" >

        <TextView
                android:id="@+id/viewpager_pop_pz_pz"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clickable="true"
                android:gravity="center"
                android:padding="@dimen/size_12dp"
                android:text="拍照"
                android:textColor="@drawable/bt_bg_selector_bgtofc4025_tv"
                android:textSize="@dimen/size_20dp" />

        <ImageView
                android:id="@+id/viewpager_pop_pz_line"
                android:layout_width="match_parent"
                android:layout_height="0.5dp"
                android:layout_below="@+id/viewpager_pop_pz_pz"
                android:background="@color/color_c9" />

        <TextView
                android:id="@+id/viewpager_pop_pz_xc"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/viewpager_pop_pz_line"
                android:clickable="true"
                android:gravity="center"
                android:padding="@dimen/size_12dp"
                android:text="从相册选取"
                android:textColor="@drawable/bt_bg_selector_bgtofc4025_tv"
                android:textSize="@dimen/size_20dp" />
    </RelativeLayout>

</RelativeLayout>

源代码下载

  • 5
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Android平台上,实现拍照或从相册选取图片上传多张可以通过以下步骤实现。首先,需要在AndroidManifest.xml文件中添加相机和存储权限。接着,在相应的Activity中,我们可以使用Intent来启动系统相机应用,或者打开系统相册应用。 如果是拍照上传,我们可以创建一个Intent对象,指定Action为MediaStore.ACTION_IMAGE_CAPTURE,然后使用startActivityForResult方法启动相机应用。拍摄完成后,系统会将照片保存在指定的URI路径上。 如果是从相册选取图片上传,我们同样可以创建一个Intent对象,指定Action为Intent.ACTION_PICK,Type为“image/*”,然后使用startActivityForResult方法启动相册应用。 接着,在onActivityResult方法中,我们可以根据requestCode和resultCode来判断是从相机还是相册返回的数据。如果是从相机返回的数据,我们可以通过指定的URI路径来获取拍摄的照片;如果是从相册返回的数据,我们可以通过data.getData()方法来获取选取的图片。 最后,我们可以将获取到的照片进行上传操作,可以是将图片转换成Bitmap对象,然后上传至服务器;或者将图片的URI路径传递给服务器进行上传。如果有多张图片需要上传,可以采用循环的方式依次处理每张图片。 总的来说,实现拍照或从相册选取图片上传多张,需要通过Intent调用系统应用获取图片,然后在onActivityResult方法中处理返回的数据,最后进行图片上传操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值