Android 拍照、压缩、水平滚动、删除

最近在项目中要搞个照片,水平方向的滚动,点击可以删除,并且支持压缩。

具体如下:

package com.example.zdd.photoutils;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;

import com.example.zdd.photoutils.adapter.BusinessSginImageViewAdapter;
import com.example.zdd.photoutils.utils.HorizontalListView;
import com.example.zdd.photoutils.utils.ToastUtil;
import com.example.zdd.photoutils.utils.ZipUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private HorizontalListView rphoto_horizon_listview;
    private Button zipFile;

    private BusinessSginImageViewAdapter businessSginImageViewAdapter;
    /**
     * 签到图片、文档保存地址
     */
    public static final String SGIN_SAVE_DIR = Environment
            .getExternalStorageDirectory().toString() + "/PhotoUtils/photos";

    public static final String SGIN_PHOTONAME = "yyyyMMddHHmmss";   //照片格式
    private File photoFile = null; //照片路径
    private String PhotoPath = null;     //照片存储路径
    private File zipphotoFile = null; //压缩包路径
    private String ZipPhotoPath = null;  //压缩包的路径
    private String PhotoName = "";      // 照片名称(照片保存在SD卡机的要加反斜杠)
    private List<Bitmap> bitmap_list = new ArrayList<>();       //存放照片的集合
    private List<String> PhotoPath_List = new ArrayList<>();    // 照片路径集合,上传字段是可以用
    public static final int ZIPPHOTO = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();

    }

    private void init() {
        rphoto_horizon_listview = (HorizontalListView) findViewById(R.id.photo_horizon_listview);
        zipFile = (Button) findViewById(R.id.zipFile);
        zipFile.setOnClickListener(this);

        //确保集合为空
        bitmap_list.clear();
        Resources res = getResources();
        Bitmap mBitmap = BitmapFactory.decodeResource(res, R.mipmap.photo_image);
        bitmap_list.add(mBitmap);
        businessSginImageViewAdapter = new BusinessSginImageViewAdapter(
                bitmap_list, this);
        businessSginImageViewAdapter.notifyDataSetChanged();
        rphoto_horizon_listview.setAdapter(businessSginImageViewAdapter);
        rphoto_horizon_listview.setOnItemClickListener(clickListener);

        //确保文件内没有照片
        photoFile = new File(SGIN_SAVE_DIR);
        if (photoFile.exists()) {
            String[] strings = photoFile.list();
            for (int i = 0; i < strings.length; i++) {
                File delFile = new File(SGIN_SAVE_DIR + "/" + strings[i]);
                delFile.delete();
            }
        } else {
            photoFile.mkdirs();
        }
    }


    private AdapterView.OnItemClickListener clickListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            if (position == bitmap_list.size() - 1) {
                ShowPickDialog();
            } else {
                ShowSginPhotoFeleteDialog(position);
            }
        }

    };

    private void ShowPickDialog() {
        // 获取当前时间
        SimpleDateFormat formatter = new SimpleDateFormat(SGIN_PHOTONAME);
        Date curDate = new Date(System.currentTimeMillis());
        PhotoName = formatter.format(curDate);
        PhotoPath = SGIN_SAVE_DIR + "/" + PhotoName + ".jpg";
        PhotoPath_List.add(PhotoPath);

        File photoFile = new File(PhotoPath);
        // 跳转相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(photoFile));
        startActivityForResult(intent, Activity.DEFAULT_KEYS_DIALER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            ToastUtil.ShowLong(this, "照片获取失败请重试...");
            bitmap_list.clear();
            Resources res = getResources();
            Bitmap mBitmap = BitmapFactory.decodeResource(res, R.mipmap.photo_image);
            bitmap_list.add(mBitmap);
            return;
        }
        switch (requestCode) {
            case Activity.DEFAULT_KEYS_DIALER: {
                try {
                    File photoSavePah = new File(PhotoPath);
                    Bitmap decodeBitmap = decodeBitmap(photoSavePah);
                    decodeBitmap.compress(Bitmap.CompressFormat.JPEG, 60,
                            new FileOutputStream(photoSavePah));
                    bitmap_list.add(bitmap_list.size() - 1, decodeBitmap);
                    setHandlerInfo(ZIPPHOTO, bitmap_list);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }


    public Bitmap decodeBitmap(File file) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取图片的宽和高
        Bitmap bitmap = BitmapFactory.decodeFile(file.getPath(), options);
        float realWidth = options.outWidth;
        float realHeight = options.outHeight;
        // 缩放比
        int scale = (int) ((realHeight > realWidth ? realHeight : realWidth) / 800);
        if (scale <= 0) {
            scale = 1;
        }
        options.inSampleSize = scale;
        options.inJustDecodeBounds = false;
        // 注意这次要把options.inJustDecodeBounds 设为 false,这次图片是要读取出来的。
        bitmap = BitmapFactory.decodeFile(file.getPath(), options);
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        return bitmap;
    }


    /**
     * 提示是否删除照片
     */
    private void ShowSginPhotoFeleteDialog(final int position) {
        new AlertDialog.Builder(this).setTitle("提示").setMessage("是否删除当前照片?")

                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        bitmap_list.remove(position);
                        businessSginImageViewAdapter.notifyDataSetChanged();
                        String sginPath = PhotoPath_List.get(position);
                        File file = new File(sginPath);
                        if (file.exists()) {
                            if (file.delete()) {
                                PhotoPath_List.remove(position);
                            }
                        }
                    }
                }).setPositiveButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

            }
        }).show();
    }

    /**
     * 弹框、上传、提示
     */
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case ZIPPHOTO:
                    List<Bitmap> sginlocathListBp = (List<Bitmap>) msg.obj;
                    addImageView(sginlocathListBp);
                    break;
                default:
                    break;
            }
        }

    };

    private void addImageView(List<Bitmap> bitmapList) {
        businessSginImageViewAdapter = new BusinessSginImageViewAdapter(
                bitmapList, this);
        businessSginImageViewAdapter.notifyDataSetChanged();
        rphoto_horizon_listview.setAdapter(businessSginImageViewAdapter);
        rphoto_horizon_listview.setOnItemClickListener(clickListener);
    }


    /**
     * 消息发送
     */
    private void setHandlerInfo(int sginType, Object content) {
        // 发送消息
        Message msg = new Message();
        msg.what = sginType;
        msg.obj = content;
        mHandler.sendMessage(msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //确保程序在返回的时候删除本地的数据
        if (photoFile.exists()) {
            String[] strings = photoFile.list();
            for (int i = 0; i < strings.length; i++) {
                File delFile = new File(SGIN_SAVE_DIR + "/" + strings[i]);
                delFile.delete();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.zipFile:
                if(bitmap_list.size()>0){
                    List<File> files = new ArrayList<File>();
                    ZipPhotoPath = SGIN_SAVE_DIR + ".zip";
                    zipphotoFile = new File(ZipPhotoPath);
                    File[] fileName = photoFile.listFiles();
                    if (fileName.length > 0) {
                        for (int i = 0; i < fileName.length; i++) {
                            files.add(fileName[i]);
                        }
                    }

                    try {
                        if(ZipUtils.zipPhotoFiles(files, zipphotoFile)){
                            ToastUtil.ShowLong(this,"文件压缩路径为:" + ZipPhotoPath);
                        }else{
                            ToastUtil.ShowLong(this,"文件压缩路失败...");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else{
                    ToastUtil.ShowLong(this,"请先拍摄照片...");
                }
                break;
        }
    }
}

主要的操作就是这些剩下的用了一些写好的控件,完成后在手机上运行如果不能用请确认应用的摄像头权限是否打开。



项目下载


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值