package com.hand.face.utils; import android.graphics.Bitmap; import android.graphics.Matrix; import android.os.Environment; import android.util.Log; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * Created by USER on 2016/12/10. */ public class FileUtil { private static final String TAG = "FileUtil"; private static final File parentPath = Environment.getExternalStorageDirectory(); private static String storagePath = ""; private static final String DST_FOLDER_NAME = ".HandImage"; private static String jpegPath = ""; /**初始化保存路径 * @return */ private static String initPath(String appPath){ if(storagePath.equals("")){ storagePath = appPath+"/" + DST_FOLDER_NAME; File f = new File(storagePath); if(!f.exists()){ f.mkdir(); } } return storagePath; } /**保存Bitmap到sdcard * @param b */ public static void saveBitmap(Bitmap b,String appPath){ //等比例宽高压缩 Matrix matrix = new Matrix(); matrix.setScale(0.7f, 0.7f); b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true); String path = initPath(appPath); long dataTake = System.currentTimeMillis(); // String dataTake = "myFace"; String jpegName = path + "/" + dataTake +".jpg"; jpegPath = jpegName; Log.i(TAG, "saveBitmap:jpegName = " + jpegName); try { FileOutputStream fout = new FileOutputStream(jpegName); BufferedOutputStream bos = new BufferedOutputStream(fout); b.compress(Bitmap.CompressFormat.JPEG, 70, bos); bos.flush(); bos.close(); Log.i(TAG, "saveBitmap成功"); } catch (IOException e) { // TODO Auto-generated catch block Log.i(TAG, "saveBitmap:失败"); e.printStackTrace(); } } public static String getSavePath(){ return jpegPath; } //剪切图片中间的正方形 指定图片某一边长 public static Bitmap centerSquareScaleBitmap(Bitmap bitmap, int edgeLength) { if(null == bitmap || edgeLength <= 0) { return null; } Bitmap result = bitmap; int widthOrg = bitmap.getWidth(); int heightOrg = bitmap.getHeight(); if(widthOrg > edgeLength && heightOrg > edgeLength) { //压缩到一个最小长度是edgeLength的bitmap int longerEdge = (int)(edgeLength * Math.max(widthOrg, heightOrg) / Math.min(widthOrg, heightOrg)); int scaledWidth = widthOrg > heightOrg ? longerEdge : edgeLength; int scaledHeight = widthOrg > heightOrg ? edgeLength : longerEdge; Bitmap scaledBitmap; try{ scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true); } catch(Exception e){ return null; } //从图中截取正中间的正方形部分。 int xTopLeft = (scaledWidth - edgeLength) / 2; int yTopLeft = (scaledHeight - edgeLength) / 2; try{ result = Bitmap.createBitmap(scaledBitmap, xTopLeft, yTopLeft, edgeLength, edgeLength); scaledBitmap.recycle(); } catch(Exception e){ return null; } } return result; } }