1. 程式人生 > >Android 多張圖片展示,仿微信圖片上傳,可以選擇多張圖片

Android 多張圖片展示,仿微信圖片上傳,可以選擇多張圖片

我們經常會遇到需要多張圖片展示上傳的需求 ,如圖
這裡寫圖片描述

這樣的需求我已經遇到過多次,個人總結一下,希望大家多多指點,支援選擇多張圖片
這裡寫圖片描述

佈局:一個GridView

 <com.zuihou.drunkenmonkey.widget.view.DirectoryScrollGridView
                    android:id="@+id/gridView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
android:layout_gravity="center_vertical" android:numColumns="3" android:padding="@dimen/margin_8" />

點選從相簿或相機選擇圖片出現彈框,彈框佈局如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:id="@+id/ll_popup" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:background="@color/homepage_type_bg" android:orientation
="vertical">
<LinearLayout android:layout_width="match_parent" android:layout_height="55dp" android:orientation="horizontal"> <Button android:id="@+id/item_popupwindows_camera" android:layout_width="match_parent" android:layout_height="55dp" android:text="拍照" android:textColor="#585858" android:textSize="@dimen/font_16" /> </LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="1px" android:layout_marginLeft="80dp" android:background="#f2f2f2" /> <LinearLayout android:layout_width="match_parent" android:layout_height="55dp" android:orientation="horizontal"> <Button android:id="@+id/item_popupwindows_Photo" android:layout_width="match_parent" android:layout_height="55dp" android:text="從相簿中選取" android:textColor="#585858" android:textSize="@dimen/font_16" /> </LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="2dp" android:background="#f3f3f3" /> <Button android:id="@+id/item_popupwindows_cancel" android:layout_width="match_parent" android:layout_height="55dp" android:text="取消" android:textColor="#585858" android:textSize="@dimen/font_16" /> </LinearLayout> </RelativeLayout>

點選從相簿或相機選擇圖片出現彈框,Activity程式碼:

 /**
     * 底部彈框選擇型別
     */
    private void pictureSelect() {
        View view = getLayoutInflater().inflate(R.layout.llj_item_popupwindows, null);
        // 設定style 控制預設dialog帶來的邊距問題
        final Dialog dialog = new Dialog(this, R.style.common_dialog);
        dialog.setContentView(view);
        dialog.show();

        Button camera = (Button) view.findViewById(R.id.item_popupwindows_camera);
        final Button photo = (Button) view.findViewById(R.id.item_popupwindows_Photo);
        Button cancel = (Button) view.findViewById(R.id.item_popupwindows_cancel);

        //手機拍照
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                photo();
                dialog.dismiss();
            }
        });

        //從手機選擇
        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectedMode;
                selectedMode = MultiImageSelectorActivity.MODE_MULTI;
                int maxNum = 3 - drr.size();
                Intent intent = new Intent(AdviceActivity.this, MultiImageSelectorActivity.class);
                // 是否顯示拍攝圖片
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
                // 最大可選擇圖片數量
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
                // 選擇模式
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);

                startActivityForResult(intent, RESULT_LOAD_IMAGE);
                dialog.dismiss();

            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        // 設定相關位置,一定要在 show()之後
        Window window = dialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.gravity = Gravity.BOTTOM;
        window.setAttributes(params);
    }

拍照:

/**
     * 拍照
     */
    public void photo() {
        try {
            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            String sdcardState = Environment.getExternalStorageState();
            String sdcardPathDir = Environment.getExternalStorageDirectory().getPath() + "/tempImage/";
            File file = null;
            if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
                // 有sd卡,是否有myImage資料夾
                File fileDir = new File(sdcardPathDir);
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                // 是否有headImg檔案
                file = new File(sdcardPathDir + System.currentTimeMillis() + ".JPEG");
            }
            if (file != null) {
                path = file.getPath();
                photoUri = Uri.fromFile(file);
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

                startActivityForResult(openCameraIntent, TAKE_PICTURE);
            }

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

選擇照片返回結果

 private static final int TAKE_PICTURE = 0;
    private static final int RESULT_LOAD_IMAGE = 1;
    private static final int CUT_PHOTO_REQUEST_CODE = 2;
    private String path = "";
    private Uri photoUri;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PICTURE:
                if (drr.size() < 3 && resultCode == -1) {
                    startPhotoZoom(photoUri);
                }
                break;
            case RESULT_LOAD_IMAGE:
                if (drr.size() < 3 && resultCode == RESULT_OK && null != data) {
                    mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                    Log.e("6666", ":" + mSelectPath);
                    Bitmap bitmap;

                    try {
                        for (String p : mSelectPath) {
                            Log.e("55555", p.toString());
                            bitmap = Bimp.revitionImageSize(p.toString());
                            PhotoActivity.bitmap.add(bitmap);
                            bitmap = Bimp.createFramedPhoto(480, 480, bitmap, (int) (dp * 1.6f));
                            bmp.add(bitmap);
                            gridviewInit();
                            //把圖片數量新增進集合,方便刪除,統計數量
                            drr.add(FileUtils.SDPATH + ".JPEG");

                            //把點陣圖轉化為字元流
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                            baos.close();
                            byte[] buffer = baos.toByteArray();
                            String[] photoImgliu = new String[1024 * 1024];
                            photoImgliu[i] = Base64.encodeToString(buffer, 0, buffer.length, Base64.DEFAULT);
                            Log.e("666", "photoLiu" + i + ":" + photoImgliu[i]);
                            i++;
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CUT_PHOTO_REQUEST_CODE:
                if (resultCode == RESULT_OK && null != data) {
                    Bitmap bitmap = Bimp.getLoacalBitmap(drr.get(drr.size() - 1));
                    PhotoActivity.bitmap.add(bitmap);
                    bitmap = Bimp.createFramedPhoto(480, 480, bitmap, (int) (dp * 1.6f));
                    bmp.add(bitmap);

                    gridviewInit();

                    try {
                        //把點陣圖轉化為字元流
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                        baos.close();
                        byte[] buffer = baos.toByteArray();
                        String[] cameralImgliu = new String[1024 * 1024];

                        cameralImgliu[i] = Base64.encodeToString(buffer, 0, buffer.length, Base64.DEFAULT);
                        Log.e("666", "camearlLiu" + i + ":" + cameralImgliu[i]);
                        i++;

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;

            default:
                break;
        }
    }

選取照片後截圖:

 private void startPhotoZoom(Uri uri) {
        try {
            // 獲取系統時間 然後將裁剪後的圖片儲存至指定的資料夾
            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
            String address = sDateFormat.format(new Date());

            if (!FileUtils.isFileExist("")) {
                FileUtils.createSDDir("");
            }

            drr.add(FileUtils.SDPATH + address + ".JPEG");
            Uri imageUri = Uri.parse("file:///sdcard/formats/" + address + ".JPEG");
            final Intent intent = new Intent("com.android.camera.action.CROP");
            // 照片URL地址
            intent.setDataAndType(uri, "image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", 480);
            intent.putExtra("outputY", 480);
            // 輸出路徑
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            // 輸出格式
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            // 不啟用人臉識別
            intent.putExtra("noFaceDetection", false);
            intent.putExtra("return-data", false);
            startActivityForResult(intent, CUT_PHOTO_REQUEST_CODE);

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

介面卡的程式碼如下:

/**
     * gridview介面卡
     */
    public class GridAdapter extends BaseAdapter {
        private LayoutInflater listContainer;
        private int selectedPosition = -1;
        private boolean shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public class ViewHolder {
            public ImageView image;
            public Button bt;
        }

        public GridAdapter(Context context) {
            listContainer = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            if (bmp.size() < 3) {
                return bmp.size() + 1;
            } else {
                return bmp.size();
            }
        }

        @Override
        public Object getItem(int arg0) {
            return null;
        }

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

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        /**
         * ListView Item設定
         */

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final int sign = position;
            GridAdapter.ViewHolder holder = null;
            if (convertView == null) {
                holder = new GridAdapter.ViewHolder();
                convertView = listContainer.inflate(R.layout.design_upload, null);
                holder.image = (ImageView) convertView.findViewById(R.id.img);
                holder.bt = (Button) convertView.findViewById(R.id.item_bt);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (position == bmp.size()) {
                holder.image.setImageBitmap(BitmapFactory.decodeResource(
                        getResources(), R.mipmap.ic_photo));
                holder.bt.setVisibility(View.GONE);
                if (position == 3) {
                    holder.image.setVisibility(View.GONE);
                }
            } else {
                holder.image.setImageBitmap(bmp.get(position));
                holder.bt.setVisibility(View.VISIBLE);
                holder.bt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PhotoActivity.bitmap.remove(sign);
                        bmp.get(sign).recycle();
                        bmp.remove(sign);
                        drr.remove(sign);

                        gridviewInit();
                    }
                });
            }
            return convertView;
        }
    }