Skip to content
  • P
    Projects
  • G
    Groups
  • S
    Snippets
  • Help

android / dayu

  • This project
    • Loading...
  • Sign in
Go to a project
  • Project
  • Repository
  • Issues 0
  • Merge Requests 0
  • Pipelines
  • Wiki
  • Snippets
  • Members
  • Activity
  • Graph
  • Charts
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
  • Files
  • Commits
  • Branches
  • Tags
  • Contributors
  • Graph
  • Compare
  • Charts
Switch branch/tag
  • dayu
  • ..
  • util
  • ConUtil.java
Find file
Normal viewHistoryPermalink
ConUtil.java 16.3 KB
Newer Older
罗翻's avatar
增加人脸识别
5b0d1c4f
 
罗翻 committed 7 years ago
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
package com.megvii.idcardlib.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
罗翻's avatar
增加人脸识别
576b34ee
 
罗翻 committed 7 years ago
16
import android.os.Environment;
罗翻's avatar
增加人脸识别
5b0d1c4f
 
罗翻 committed 7 years ago
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.view.Gravity;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.megvii.idcardlib.R;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

public class ConUtil {

罗翻's avatar
增加人脸识别
905c2635
 
罗翻 committed 7 years ago
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
    /**
     * 根据byte数组,生成文件
     */
    public static String saveJPGFile(Context mContext, byte[] data, String key) {
        if (data == null)
            return null;

        File mediaStorageDir = mContext.getExternalFilesDir(Constant.cacheImage);

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            String jpgFileName = System.currentTimeMillis() + "" + new Random().nextInt(1000000) + "_" + key + ".jpg";
            fos = new FileOutputStream(mediaStorageDir + "/" + jpgFileName);
            bos = new BufferedOutputStream(fos);
            bos.write(data);
            return mediaStorageDir.getAbsolutePath() + "/" + jpgFileName;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 根据byte数组,生成文件
     */
    public static File saveJPG(Context mContext, byte[] data, String key) {
        if (data == null)
            return null;

罗翻's avatar
增加人脸识别
576b34ee
 
罗翻 committed 7 years ago
92 93 94 95 96 97 98
//        File mediaStorageDir = mContext.getExternalFilesDir(Constant.cacheImage);
        String jpgFileName = System.currentTimeMillis() + "" + new Random().nextInt(1000000) + "_" + key + ".jpg";
//        if (!mediaStorageDir.exists()) {
//            if (!mediaStorageDir.mkdirs()) {
//                return null;
//            }
//        }
罗翻's avatar
增加人脸识别
905c2635
 
罗翻 committed 7 years ago
99

罗翻's avatar
修改人脸识别存储图片的兼容性
6fa1806d
 
罗翻 committed 6 years ago
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
        File file;
        if (sdCardExist) {
            file = new File(Environment.getExternalStorageDirectory() + "/dayu/");
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(file, jpgFileName);
        } else {
            file = new File(mContext.getCacheDir() + "/dayu/");
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(file, jpgFileName);
        }
罗翻's avatar
增加人脸识别
905c2635
 
罗翻 committed 7 years ago
116 117 118
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
罗翻's avatar
增加人脸识别
576b34ee
 
罗翻 committed 7 years ago
119
            fos = new FileOutputStream(file.getAbsolutePath());
罗翻's avatar
增加人脸识别
905c2635
 
罗翻 committed 7 years ago
120 121
            bos = new BufferedOutputStream(fos);
            bos.write(data);
罗翻's avatar
增加人脸识别
576b34ee
 
罗翻 committed 7 years ago
122
            return file;
罗翻's avatar
修改人脸识别存储图片的兼容性
6fa1806d
 
罗翻 committed 6 years ago
123

罗翻's avatar
增加人脸识别
905c2635
 
罗翻 committed 7 years ago
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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void copyModels(Context context) {
        File dstModelFile = new File(context.getExternalFilesDir(null), "model");
        if (dstModelFile.exists()) {
            return;
        }

        try {
            String tmpFile = "model";
            BufferedInputStream inputStream = new BufferedInputStream(context.getAssets().open(tmpFile));
            BufferedOutputStream foutputStream = new BufferedOutputStream(new FileOutputStream(dstModelFile));

            byte[] buffer = new byte[1024];
            int readcount = -1;
            while ((readcount = inputStream.read(buffer)) != -1) {
                foutputStream.write(buffer, 0, readcount);
            }
            foutputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static byte[] readModel(Context context) {
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int count = -1;
        try {
            inputStream = context.getResources().openRawResource(R.raw.livenessmodel);
            while ((count = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byteArrayOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return byteArrayOutputStream.toByteArray();
    }

    public static String getUUIDString(Context mContext) {
        String KEY_UUID = "key_uuid";
        SharedUtil sharedUtil = new SharedUtil(mContext);
        String uuid = sharedUtil.getStringValueByKey(KEY_UUID);
        if (uuid != null && uuid.trim().length() != 0)
            return uuid;

        uuid = UUID.randomUUID().toString();
        uuid = Base64.encodeToString(uuid.getBytes(), Base64.DEFAULT);
        sharedUtil.saveStringValue(KEY_UUID, uuid);
        return uuid;
    }

    public static String getPhoneNumber(Context mContext) {
        TelephonyManager phoneMgr = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        return phoneMgr.getLine1Number();
    }

    public static String getDeviceID(Context mContext) {
        TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getDeviceId();
    }

    public static String getMacAddress(Context mContext) {
        WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        String address = info.getMacAddress();
        if (address != null && address.length() > 0) {
            address = address.replace(":", "");
        }
        return address;
    }

    /**
     * 获取bitmap的灰度图像
     */
    public static byte[] getGrayscale(Bitmap bitmap) {
        if (bitmap == null)
            return null;

        byte[] ret = new byte[bitmap.getWidth() * bitmap.getHeight()];
        for (int j = 0; j < bitmap.getHeight(); ++j)
            for (int i = 0; i < bitmap.getWidth(); ++i) {
                int pixel = bitmap.getPixel(i, j);
                int red = ((pixel & 0x00FF0000) >> 16);
                int green = ((pixel & 0x0000FF00) >> 8);
                int blue = pixel & 0x000000FF;
                ret[j * bitmap.getWidth() + i] = (byte) ((299 * red + 587 * green + 114 * blue) / 1000);
            }
        return ret;
    }

    /**
     * 读取图片属性:旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 旋转图片
     *
     * @param angle
     * @param bitmap
     * @return Bitmap
     */
    public static Bitmap rotateImage(int angle, Bitmap bitmap) {
        // 图片旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 得到旋转后的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }

    private static Bitmap getBitMap(String fileSrc, int dstWidth) {
        if (dstWidth == -1) {
            return BitmapFactory.decodeFile(fileSrc);
        }
        // 获取图片的宽和高
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(fileSrc, options);

        // 压缩图片
        options.inSampleSize = Math.max(1,
                (int) (Math.max((double) options.outWidth / dstWidth, (double) options.outHeight / dstWidth)));
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(fileSrc, options);
    }

    /**
     * 压缩图
     */
    public static Bitmap getBitmapConsiderExif(String imagePath) {

        // 获取照相后的bitmap
        // Bitmap tmpBitmap = BitmapFactory.decodeFile(imagePath);
        Bitmap tmpBitmap = getBitMap(imagePath, 800);
        if (tmpBitmap == null)
            return null;
        Matrix matrix = new Matrix();
        matrix.postRotate(readPictureDegree(imagePath));
        tmpBitmap = Bitmap.createBitmap(tmpBitmap, 0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight(), matrix, true);
        tmpBitmap = tmpBitmap.copy(Config.ARGB_8888, true);

        int hight = tmpBitmap.getHeight() > tmpBitmap.getWidth() ? tmpBitmap.getHeight() : tmpBitmap.getWidth();

        float scale = hight / 800.0f;

        if (scale > 1) {
            tmpBitmap = Bitmap.createScaledBitmap(tmpBitmap, (int) (tmpBitmap.getWidth() / scale),
                    (int) (tmpBitmap.getHeight() / scale), false);
        }
        return tmpBitmap;
    }

    /**
     * 切图
     */
    public static Bitmap cropImage(RectF rect, Bitmap bitmap) {
        float width = rect.width() * 2;
        if (width > bitmap.getWidth()) {
            width = bitmap.getWidth();
        }

        float hight = rect.height() * 2;
        if (hight > bitmap.getHeight()) {
            hight = bitmap.getHeight();
        }

        float l = rect.centerX() - (width / 2);
        if (l < 0) {
            l = 0;
        }
        float t = rect.centerY() - (hight / 2);
        if (t < 0) {
            t = 0;
        }
        if (l + width > bitmap.getWidth()) {
            width = bitmap.getWidth() - l;
        }
        if (t + hight > bitmap.getHeight()) {
            hight = bitmap.getHeight() - t;
        }

        return Bitmap.createBitmap(bitmap, (int) l, (int) t, (int) width, (int) hight);

    }

    /**
     * 切图
     */
    public static Bitmap cutImage(RectF rect, String imagePath) {
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        return cropImage(rect, bitmap);

    }

    /**
     * 照相机拍照后照片存储路径
     */
    public static File getOutputMediaFile(Context mContext) {
        File mediaStorageDir = mContext.getExternalFilesDir(Constant.cacheCampareImage);
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;

        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
        return mediaFile;
    }

    /**
     * 隐藏软键盘
     */
    public static void isGoneKeyBoard(Activity activity) {
        if (activity.getCurrentFocus() != null) {
            // 隐藏软键盘
            ((InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                    activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 输出toast
     */
    public static void showToast(Context context, String str) {
        if (context != null) {
            Toast toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);
            // 可以控制toast显示的位置
            toast.setGravity(Gravity.TOP, 0, 30);
            toast.show();
        }
    }

    /**
     * 输出长时间toast
     */
    public static void showLongToast(Context context, String str) {
        if (context != null) {
            Toast toast = Toast.makeText(context, str, Toast.LENGTH_LONG);
            // 可以控制toast显示的位置
            toast.setGravity(Gravity.TOP, 0, 30);
            toast.show();
        }
    }

    /**
     * 获取APP版本名
     */
    public static String getVersionName(Context context) {
        try {
            String versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
            return versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 镜像旋转
     */
    public static Bitmap convert(Bitmap bitmap, boolean mIsFrontalCamera) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Bitmap newbBitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
        Canvas cv = new Canvas(newbBitmap);
        Matrix m = new Matrix();
        // m.postScale(1, -1); //镜像垂直翻转
        if (mIsFrontalCamera) {
            m.postScale(-1, 1); // 镜像水平翻转
        }
        // m.postRotate(-90); //旋转-90度
        Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, w, h, m, true);
        cv.drawBitmap(bitmap2, new Rect(0, 0, bitmap2.getWidth(), bitmap2.getHeight()), new Rect(0, 0, w, h), null);
        return newbBitmap;
    }

    /**
     * 保存bitmap至指定Picture文件夹
     */
    public static String saveBitmap(Context mContext, Bitmap bitmaptosave) {
        if (bitmaptosave == null)
            return null;

        File mediaStorageDir = mContext.getExternalFilesDir(Constant.cacheImage);

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }
        // String bitmapFileName = System.currentTimeMillis() + ".jpg";
        String bitmapFileName = System.currentTimeMillis() + "";
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(mediaStorageDir + "/" + bitmapFileName);
            boolean successful = bitmaptosave.compress(Bitmap.CompressFormat.JPEG, 75, fos);

            if (successful)
                return mediaStorageDir.getAbsolutePath() + "/" + bitmapFileName;
            else
                return null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 时间格式化(格式到秒)
     */
    public static String getFormatterTime(long time) {
        Date d = new Date(time);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String data = formatter.format(d);
        return data;
    }
罗翻's avatar
增加人脸识别
5b0d1c4f
 
罗翻 committed 7 years ago
504 505

}