在android开发中, 在一些编辑个人信息的时候,经常会有头像这么一个东西,就两个方面,调用系统相机拍照,调用系统图库获取图片.但是往往会遇到各种问题:

1.oom

2.图片方向不对

3.activity result 的时候data == null

4.调用图库的时候没找到软件

嘿嘿..开代码:

首先是调用系统拍照,和图库的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package com.chzh.fitter.util;
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.widget.Toast;
//在onActivityResult方法中根据requestCode和resultCode来获取当前拍照的图片地址。
//注意:这里有个问题,在有些机型当中(如SamsungI939、note2等)遇见了当拍照并存储之后,intent当中得到的data为空:
/**
 * data = null 的情况主要是由于拍照的时候横屏了,导致重新create, 普通的解决方法可以在sharedpreference里面保存拍照文件的路径(onSaveInstance保存),
 * 在onRestoreSaveInstance里面在获取出来.
 * 最简单的可以用fileUtil 里面的一个静态变量保存起来..
 * */
public class CameraUtil {
    private static final String IMAGE_TYPE = "image/*";
    private Context mContext;
    public CameraUtil(Context context) {
        mContext = context;
    }
    /**
     * 打开照相机
     * @param activity 当前的activity
     * @param requestCode 拍照成功时activity forResult 的时候的requestCode
     * @param photoFile 拍照完毕时,图片保存的位置
     */
    public void openCamera(Activity activity, int requestCode, File photoFile) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        activity.startActivityForResult(intent, requestCode);
    }
    /**
     * 本地照片调用
     * @param activity
     * @param requestCode
     */
    public void openPhotos(Activity activity, int requestCode) {
        if (openPhotosNormal(activity, requestCode) && openPhotosBrowser(activity, requestCode) && openPhotosFinally());
    }
    /**
     * PopupMenu打开本地相册.
     */
    private boolean openPhotosNormal(Activity activity, int actResultCode) {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                IMAGE_TYPE);
        try {
            activity.startActivityForResult(intent, actResultCode);
        catch (android.content.ActivityNotFoundException e) {
            return true;
        }
        return false;
    }
    /**
     * 打开其他的一文件浏览器,如果没有本地相册的话
     */
    private boolean openPhotosBrowser(Activity activity, int requestCode) {
        Toast.makeText(mContext, "没有相册软件,运行文件浏览器", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
        intent.setType(IMAGE_TYPE); // 查看类型 String IMAGE_UNSPECIFIED =
                                    // "image/*";
        Intent wrapperIntent = Intent.createChooser(intent, null);
        try {
            activity.startActivityForResult(wrapperIntent, requestCode);
        catch (android.content.ActivityNotFoundException e1) {
            return true;
        }
        return false;
    }
    /**
     * 这个是找不到相关的图片浏览器,或者相册
     */
    private boolean openPhotosFinally() {
        Toast.makeText(mContext, "您的系统没有文件浏览器或则相册支持,请安装!", Toast.LENGTH_LONG).show();
        return false;
    }
    /**
     * 获取从本地图库返回来的时候的URI解析出来的文件路径
     * @return
     */
    public static String getPhotoPathByLocalUri(Context context, Intent data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(selectedImage,
                filePathColumn, nullnullnull);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        return picturePath;
    }
}

  接下来是解决oom的

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package com.chzh.fitter.util;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.net.Uri;
import android.util.Log;
import android.widget.ImageView;
import com.androidquery.util.AQUtility;
/**
 * @author jarrahwu
 *
 */
public class ImageUtil {
    /**
     * Utility method for downsampling images.
     *
     * @param path
     *            the file path
     * @param data
     *            if file path is null, provide the image data directly
     * @param target
     *            the target dimension
     * @param isWidth
     *            use width as target, otherwise use the higher value of height
     *            or width
     * @param round
     *            corner radius
     * @return the resized image
     */
    public static Bitmap getResizedImage(String path, byte[] data, int target,
            boolean isWidth, int round) {
        Options options = null;
        if (target > 0) {
            Options info = new Options();
            info.inJustDecodeBounds = true;
            //设置这两个属性可以减少内存损耗
            info.inInputShareable = true;
            info.inPurgeable = true;
            decode(path, data, info);
            int dim = info.outWidth;
            if (!isWidth)
                dim = Math.max(dim, info.outHeight);
            int ssize = sampleSize(dim, target);
            options = new Options();
            options.inSampleSize = ssize;
        }
        Bitmap bm = null;
        try {
            bm = decode(path, data, options);
        catch (OutOfMemoryError e) {
            L.red(e.toString());
            e.printStackTrace();
        }
        if (round > 0) {
            bm = getRoundedCornerBitmap(bm, round);
        }
        return bm;
    }
    private static Bitmap decode(String path, byte[] data,
            BitmapFactory.Options options) {
        Bitmap result = null;
        if (path != null) {
            result = decodeFile(path, options);
        else if (data != null) {
            // AQUtility.debug("decoding byte[]");
            result = BitmapFactory.decodeByteArray(data, 0, data.length,
                    options);
        }
        if (result == null && options != null && !options.inJustDecodeBounds) {
            AQUtility.debug("decode image failed", path);
        }
        return result;
    }
    private static Bitmap decodeFile(String path, BitmapFactory.Options options) {
        Bitmap result = null;
        if (options == null) {
            options = new Options();
        }
        options.inInputShareable = true;
        options.inPurgeable = true;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
            FileDescriptor fd = fis.getFD();
            // AQUtility.debug("decoding file");
            // AQUtility.time("decode file");
            result = BitmapFactory.decodeFileDescriptor(fd, null, options);
            // AQUtility.timeEnd("decode file", 0);
        catch (IOException e) {
            Log.error("TAG",e.toString())
        finally {
            fis.close()
        }
        return result;
    }
    private static int sampleSize(int width, int target) {
        int result = 1;
        for (int i = 0; i < 10; i++) {
            if (width < target * 2) {
                break;
            }
            width = width / 2;
            result = result * 2;
        }
        return result;
    }
    /**
     * 获取圆角的bitmap
     * @param bitmap
     * @param pixels
     * @return
     */
    private static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(00, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;
        paint.setAntiAlias(true);
        canvas.drawARGB(0000);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }
    /**
     * auto fix the imageOrientation
     * @param bm source
     * @param iv imageView  if set invloke it's setImageBitmap() otherwise do nothing
     * @param uri image Uri if null user path
     * @param path image path if null use uri
     */
    public static Bitmap autoFixOrientation(Bitmap bm, ImageView iv, Uri uri,String path) {
        int deg = 0;
        try {
            ExifInterface exif = null;
            if (uri == null) {
                exif = new ExifInterface(path);
            }
            else if (path == null) {
                exif = new ExifInterface(uri.getPath());
            }
            if (exif == null) {
                Log.error("TAG","exif is null check your uri or path");
                return bm;
            }
            String rotate = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
            int rotateValue = Integer.parseInt(rotate);
            System.out.println("orientetion : " + rotateValue);
            switch (rotateValue) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                deg = 90;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                deg = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                deg = 270;
                break;
            default:
                deg = 0;
                break;
            }
        catch (Exception ee) {
            Log.d("catch img error""return");
            if(iv != null)
            iv.setImageBitmap(bm);
            return bm;
        }
        Matrix m = new Matrix();
        m.preRotate(deg);
        bm = Bitmap.createBitmap(bm, 00, bm.getWidth(), bm.getHeight(), m, true);
        //bm = Compress(bm, 75);
        if(iv != null)
            iv.setImageBitmap(bm);
        return bm;
    }
}

  

  如果想要代码Demo的话,可以留言.有什么坑爹的地方,多多拍砖..over.

一站式解决,Android 拍照 图库的各种问题相关推荐

  1. 彻底解决Android 拍照 内存溢出 Out of Memory的问题

    内存溢出相信做过编程的人都知道一二,这里说Android 内存溢出的问题:.问题描述:Android下的相机在独自使用时,拍照没有问题,通过我们的代码调用时,也正常,但是更换了不同厂商的平板,ROM由 ...

  2. 解决Android拍照保存在系统相册不显示的问题

    可能大家都知道我们保存相册到Android手机的时候,然后去打开系统图库找不到我们想要的那张图片,那是因为我们插入的图片还没有更新的缘故,先讲解下插入系统图库的方法吧,很简单,一句代码就能实现 [ja ...

  3. 解决Android 拍照图片被旋转问题

    今天在项目中做拍照上传头像相关, 但调用系统相机拍照得到的图片总是旋转90度, 在网上找到了两种答案: 第一种如下, 无奈得到的旋转角度总是 0 度 , 无法解决旋转问题 //读取图片旋转角度publ ...

  4. android拍照模糊,解决Android拍照并显示在ImageView中变模糊

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 public class ImageThumbnail { public static int reckonThumbnail(int oldWidth, ...

  5. Android 拍照和图库功能(适配Android 6.0和7.0系统和华为机型问题)

    众所周知,调用相机拍照和图库中获取图片的功能,基本上是每个程序App必备的. 实现适配Android每个版本,国内手机,要处理的问题却也不少.例如:Android6.0权限问题,Android7.0 ...

  6. 解决Android图库不识别.nomedia的问题

    解决Android图库不识别.nomedia的问题 参考文章: (1)解决Android图库不识别.nomedia的问题 (2)https://www.cnblogs.com/TianFang/arc ...

  7. Android 7.0 获取相机拍照图片,适配三星手机拍照,解决三星手机拍照屏幕旋转,判断设备是否有摄像头

    方法1 新建/res/xml/file_paths: <?xml version="1.0" encoding="utf-8"?> <path ...

  8. 前端html input =“file“ ios/安卓解决无法选择图库/拍照问题

    前端html input ="file" ios/安卓解决无法选择图库/拍照问题 背景 解决办法 延申 背景 在使用input上传图片的时候,有时候会出现安卓能拍照和选择图库,而i ...

  9. android上传图片被旋转,解决android有的手机拍照后上传图片被旋转的问题

    需求:做仿新浪发微博的项目,能够上传图片还有两外一个项目用到手机拍摄图片,这两个都需要把图片上传到服务器 遇到问题:有的手机拍摄的图片旋转90度,有的图片旋转了180度,有的手机是正常的,服务器要求的 ...

最新文章

  1. 创客集结号_你知道单机片和Arduino之间的区别吗
  2. java 大臣的旅费_PREV-9-蓝桥杯-历届试题-大臣的旅费-java
  3. Linux内核的同步机制---自旋锁
  4. ios 监听一个控制器的属性_OC观察者模式之KVO的使用与思考
  5. .net core WebApi 使用Swagger生成API文档
  6. [react] 如何更新组件的状态?
  7. nginx 强制跳转https_Nginx服务器环境手动安装Discuz! Q非详细教程
  8. BZOJ 4242 水壶(BFS建图+最小生成树+树上倍增)
  9. 网络图片 base64 java_java图片转base64和真实的结果不一样
  10. Spring Boot 学习系列(07)—properties文件读取
  11. 服务器端配置nodejs环境(使用pm2进程管理运行)
  12. numpy 矩阵拼接_Python实践代码总结第10集(Numpy)
  13. 深入探討 SCOM 2007 管理技術
  14. firefox + pentadactyl 实现纯绿色高效易扩展浏览器(同时实现修改默认状态栏样式)...
  15. 通信协议 - ARINC615A加卸载协议
  16. android 源代码 毛笔,android中实现毛笔效果(View 中绘图)
  17. 了解资本与公司年报、财报
  18. win10计算机管理看不见蓝牙,Win10设备管理器找不到蓝牙设备的解决方案
  19. 热感觉、热舒适、热满意度、热需求与热偏好
  20. E575: viminfo: Illegal starting char in line:(z)

热门文章

  1. WCF 第四章 绑定 netMsmqBinding
  2. mysql常用快速查询修改操作
  3. Activity加载View调用顺序
  4. 小强系列之大话移动测试
  5. PDC Party 即将在东莞登场
  6. Silverlight中摄像头的运用—part2
  7. SQL2005的配置
  8. java 代码执行el,专属于java的漏洞——EL表达式注入
  9. SQL中的left outer join,inner join,right outer join用法 (左右内连接)
  10. linux下搭建go环境--问题记录