显示多张照片android
2018-09-09 16:46:43 fenhailan 阅读数 563

Android通过调用一次系统相机,拍摄多张照片并返回给activity,其实Android时没有提供这样的api的,但是可以通过其他的方式实现这个功能。

思路:在调用系统相机之前记下时间戳,等拍照后去系统图片媒体库中查询图片创建时间大于时间戳的图片。

调用系统拍照,拍多张:

 intent.setAction(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
 activity.startActivityForResult(intent, TAKEONCAMERA);

调用系统拍一张的方法是,还有有点区别的:

Intent intentCamera = new Intent();
intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
activity.startActivityForResult(intentCamera, requestCode);

拍照完毕后返回到activity会回调onActivityResult方法,在方法里进行图片的查找:

    /**
     * 获取拍摄的照片,在调用takeOnCamera之后返回界面时调用该方法。
     */
    public static List<String> getTakePhoto(Context context){

        Cursor cursor = null;
        try {
            cursor = context.getContentResolver()
                    .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, PROJECTION,
                            null, null,
                            MediaStore.Images.Media.DATE_ADDED +  " DESC LIMIT 0,30");
            if (cursor != null){
                List<String> photoList = new ArrayList<>(cursor.getCount());
                cursor.moveToFirst();
                while (!cursor.isAfterLast()){
                    long createTemp = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED));
                    if (isAfterStart(startTemp, createTemp)){
                        photoList.add(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)));
                    }
                    cursor.moveToNext();
                }
                return photoList;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (cursor != null){
                cursor.close();
            }
        }
        return null;
    }

完整的代码:

/**
 * -  相册或拍照选取多张照片工具类
 * <p>
 * Created by Sunxy on 2018/9/8.
 */
public class GetPhotoUtils {

    public static final int TAKEONCAMERA = 1002;

    private  static final String[] PROJECTION = {MediaStore.Images.Media._ID,
            MediaStore.Images.Media.DATE_ADDED,
            MediaStore.Images.Media.DATA};

    private static long startTemp = Long.MAX_VALUE;
    private static int state = 0;


    /**
     * 得到手机中所有的照片(async)
     */
    public static List<String> getAllPhoto(Context context){

        Cursor cursor = null;
        try {
            cursor = context.getContentResolver()
                    .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, PROJECTION,
                            null, null,
                            MediaStore.Images.Media.DATE_ADDED +  " DESC");
            if (cursor != null){
                List<String> photoList = new ArrayList<>(cursor.getCount());
                cursor.moveToFirst();
                while (!cursor.isAfterLast()){
                    photoList.add(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)));
                    cursor.moveToNext();
                }
                return photoList;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (cursor != null){
                cursor.close();
            }
        }
        return null;
    }

    /**
     * 调手机相机拍多张照片
     */
    public static void takeOnCamera(Activity activity) {
        //打开相机之前,记录时间1
        startTemp = System.currentTimeMillis();
        Intent intent = new Intent();
        //此处之所以诸多try catch,是因为各大厂商手机不确定哪个方法
        try {
            intent.setAction(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
            activity.startActivityForResult(intent, TAKEONCAMERA);
        } catch (Exception e) {
            try {
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE_SECURE);
                activity.startActivityForResult(intent, TAKEONCAMERA);
            } catch (Exception e1) {
                try {
                    intent.setAction(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE);
                    activity.startActivityForResult(intent, TAKEONCAMERA);
                } catch (Exception ell) {
                    ToastUtils.showToast(activity, "打开摄像机失败,请从相册选择照片");
                }
            }
        }
    }


    /**
     * 获取拍摄的照片,在调用takeOnCamera之后返回界面是调用该方法。
     */
    public static List<String> getTakePhoto(Context context){

        Cursor cursor = null;
        try {
            cursor = context.getContentResolver()
                    .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, PROJECTION,
                            null, null,
                            MediaStore.Images.Media.DATE_ADDED +  " DESC LIMIT 0,30");
            if (cursor != null){
                List<String> photoList = new ArrayList<>(cursor.getCount());
                cursor.moveToFirst();
                while (!cursor.isAfterLast()){
                    long createTemp = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED));
                    if (isAfterStart(startTemp, createTemp)){
                        photoList.add(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)));
                    }
                    cursor.moveToNext();
                }
                return photoList;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (cursor != null){
                cursor.close();
            }
        }
        return null;
    }

    /**
     * 判断照片创建时间是不是在开始之后,
     * 时间戳可能是10位或者是13位,要先统一位数
     *
     */
    private static boolean isAfterStart(long startTemp, long createTemp){
        if (state == 0){
            int startTempLength = String.valueOf(startTemp).length();
            int createTempLength = String.valueOf(createTemp).length();
            if (startTempLength == createTempLength){
                state = 1;
            }else if(startTempLength == 10 && createTempLength == 13){
                state = 2;
            }else if(startTempLength == 13 && createTempLength == 10){
                state = 3;
            }
        }
        if (state == 2){
            startTemp = startTemp * 1000;
        }else if(state == 3){
            startTemp = startTemp / 1000;
        }
        return createTemp - startTemp >= 0;
    }

}

 

2016-08-23 20:37:07 JimTrency 阅读数 7014

你们会觉得这没什么好讲的,一般都导入相应的项目就ok了,但我个人觉得,这会造成很多无用代码。于是乎,我又去看源码,了解思想后,这次自己写了项目,先说说思想及注意事项:
1.通过ContentResolver 获取手机里面的所有图片的路径
2.把获取的图片,展示在GridView中

其实,就这么简单,好处是:维护起来方便。

注意事项:
从相册导入的图片,有大有小,太大可能撑爆内存,或者GridView滚动时,很卡。
那怎么解决呢,用picasso-2.5.2.jar就行,当然你用我前面的经典压缩图片方法也是一样的。
先来看重点代码:
Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver mContentResolver = MainActivity.this
.getContentResolver();

    // 只查询jpeg和png的图片
    Cursor mCursor = mContentResolver.query(mImageUri, null,
            MediaStore.Images.Media.MIME_TYPE + "=? or "
                    + MediaStore.Images.Media.MIME_TYPE + "=?",
            new String[]{"image/jpeg", "image/png"},
            MediaStore.Images.Media.DATE_MODIFIED);
      while (mCursor.moveToNext()) {
        // 获取图片的路径
        String path = mCursor.getString(mCursor
                .getColumnIndex(MediaStore.Images.Media.DATA));
        list.add(path);
    }

图片的处理:
Picasso.with(context).load(new File(list.get(position)))
.resize(200, 200).centerCrop().into(viewHolder.imageView);

下面有两个链接,一个是github上的,别人写的一个项目,我还觉得可以,该项目链接地址如下:
https://github.com/lovetuzitong/MultiImageSelector
后面这个是我Demo的例子,但没怎么完善,只是实现的基本功能,后续都比较简单了,自己可以完成。
链接地址如下:
http://download.csdn.net/detail/jimtrency/9610886

2016-09-12 16:33:32 miaozhenzhong 阅读数 620

1.利用LruCache、DiskLruCache实现图片的加载,避免OOM
2.引用开源库https://github.com/pengjianbo/GalleryFinal,实现从相册中选择图片、拍照进而进行上传,图片上传可以


private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

private final OkHttpClient client = new OkHttpClient();
private void uploadImg() {

        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (int i = 0; i <mImgUrls.size() ; i++) {
            File f=new File(mImgUrls.get(i));
            if (f!=null) {
                builder.addFormDataPart("img", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
            }
        }
           //添加其它信息
//        builder.addFormDataPart("time",takePicTime);
//        builder.addFormDataPart("mapX", SharedInfoUtils.getLongitude());
//        builder.addFormDataPart("mapY",SharedInfoUtils.getLatitude());
//        builder.addFormDataPart("name",SharedInfoUtils.getUserName());


        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url(Constant.BASE_URL)//地址
                .post(requestBody)//添加请求体
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                
                System.out.println("上传失败:e.getLocalizedMessage() = " + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                
                System.out.println("上传照片成功:response = " + response.body().string());
                ToastCustom.makeText(PictureListActivity.this, "上传成功", Toast.LENGTH_LONG).show();
              

            }
        });

    }
2017-02-15 16:12:00 weixin_33974433 阅读数 21
1331884-c620aab50716a731.png
2017-04-26 13:33:33 tiramisu_ljh 阅读数 2139

http://blog.csdn.net/sanyang730/article/details/51317083

http://blog.csdn.net/moniteryao/article/details/52683691

private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

private final OkHttpClient client = new OkHttpClient();

private void uploadImg() {

        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (int i = 0; i <mImgUrls.size() ; i++) {
            File f=new File(mImgUrls.get(i));
            if (f!=null) {
                builder.addFormDataPart("img", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
            }
        }

           //添加其它信息
//        builder.addFormDataPart("time",takePicTime);
//        builder.addFormDataPart("mapX", SharedInfoUtils.getLongitude());
//        builder.addFormDataPart("mapY",SharedInfoUtils.getLatitude());
//        builder.addFormDataPart("name",SharedInfoUtils.getUserName());


        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url(Constant.BASE_URL)//地址
                .post(requestBody)//添加请求体
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                
                System.out.println("上传失败:e.getLocalizedMessage() = " + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                
                System.out.println("上传照片成功:response = " + response.body().string());
                ToastCustom.makeText(PictureListActivity.this, "上传成功", Toast.LENGTH_LONG).show();
              

            }
        });

    }


没有更多推荐了,返回首页