1.权限处理代码
@Override
public void onRequestPermissionsResult(
int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == Permission.REQUEST_CODE) {
for (int grantResult : grantResults) {
if (grantResult != PackageManager.PERMISSION_GRANTED) {
Log.e("Permission","授权失败!");
// 授权失败,退出应用
this.finish();
return;
}
}
}
}
private void requestWritePermission(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},WRITE_PERMISSION);
}
}
}
调用
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWritePermission();
}
2.文件储存工具代码
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FileUtils {
private String TAG = FileUtils.class.getSimpleName();
public static String SDPATH = Environment.getExternalStorageDirectory() + "/.photocomb/";
public static String DBName = "privalbum.db";
public static String DBPATH = "/data/data/com.cm.photocomb/databases/" + DBName;
/**
* 操作成功返回值
*/
public static final int SUCCESS = 0;
/**
* 操作失败返回值
*/
public static final int FAILED = -1;
private static final int BUF_SIZE = 32 * 1024; // 32KB
/**
*
* 方法名: </br>
* 详述: <返回录音文件路径/br>
* 创建时间:2015-4-10</br>
*
* @return
*/
public static String getFileName() {
String path = SDPATH;
File file = new File(path);
file.mkdirs();
path += System.currentTimeMillis();
return path;
}
public static byte[] Bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
private String generate(String key) {
if (TextUtils.isEmpty(key)) {
return "";
}
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(key.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
/**
* bytes转换成十六进制字符串
*
* @param b 数组
* b byte数组
* @return String 每个Byte值之间空格分隔
*/
public static String byte2HexStr(byte[] b) {
String stmp = "";
StringBuilder sb = new StringBuilder("");
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0xFF);
sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
sb.append(" ");
}
return sb.toString().toUpperCase().trim();
}
/**
* bytes字符串转换为Byte值
*
* @param src src Byte字符串,每个Byte之间没有分隔符
* @return byte[]
*/
public static byte[] hexStr2Bytes(String src) {
int m = 0, n = 0;
int l = src.length() / 2;
System.out.println(l);
byte[] ret = new byte[l];
for (int i = 0; i < l; i++) {
m = i * 2 + 1;
n = m + 1;
ret[i] = Byte.decode("0x" + src.substring(i * 2, m) + src.substring(m, n));
}
return ret;
}
public static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'F' };
public static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
sb.append(HEX_DIGITS[b[i] & 0x0f]);
}
return sb.toString();
}
public static String md5sum(String filename) {
if (TextUtils.isEmpty(filename)) {
return null;
}
InputStream fis;
byte[] buffer = new byte[1024];
int numRead = 0;
MessageDigest md5;
try {
fis = new FileInputStream(filename);
md5 = MessageDigest.getInstance("MD5");
while ((numRead = fis.read(buffer)) > 0) {
md5.update(buffer, 0, numRead);
}
fis.close();
return toHexString(md5.digest());
} catch (Exception e) {
return null;
}
}
public static void saveBitmap(Bitmap bm, String picName) {
Log.e("", "保存图片");
try {
File f = new File(picName);
if (f.exists()) {
f.delete();
}
FileOutputStream out = new FileOutputStream(f);
if (bm != null) {
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
}
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean saveBitmap(Bitmap bitmap, File file) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (file.exists()) {
file.delete();
}
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public static File createSDDir(String dirName) throws IOException {
File dir = new File(SDPATH + dirName);
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
dir.mkdir();
System.out.println("createSDDir:" + dir.getAbsolutePath());
System.out.println("createSDDir:" + dir.mkdir());
}
return dir;
}
public static boolean isFileExist(String fileName) {
File file = new File(SDPATH + fileName);
file.isFile();
return file.exists();
}
public static void delFile(String fileName) {
File file = new File(SDPATH + fileName);
if (file.isFile()) {
file.delete();
}
file.exists();
}
public static void deleteDir() {
File dir = new File(SDPATH);
if (dir == null || !dir.exists() || !dir.isDirectory())
return;
for (File file : dir.listFiles()) {
if (file.isFile())
file.delete(); //
else if (file.isDirectory())
deleteDir(); // 递规的方式删除文件夹
}
dir.delete();// 删除目录本身
}
/**
*
* 方法名: </br>
* 详述: 判断文件是否存在</br>
* 创建时间:2015年11月13日</br>
*
* @param path
* @return
*/
public static boolean fileIsExists(String path) {
try {
File f = new File(path);
if (!f.exists()) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
/**
* 删除单个文件
*
* @param sPath
* 被删除文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public static boolean deleteFile(String sPath) {
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
return true;
}
return false;
}
/**
* 删除目录(文件夹)以及目录下的文件
*
* @param sPath
* 被删除目录的文件路径
* @return 目录删除成功返回true,否则返回false
*/
public static boolean deleteDirectory(String sPath) {
if (TextUtils.isEmpty(sPath)) {
return false;
}
boolean flag;
// 如果sPath不以文件分隔符结尾,自动添加文件分隔符
if (!sPath.endsWith(File.separator)) {
sPath = sPath + File.separator;
}
File dirFile = new File(sPath);
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if (!dirFile.exists() || !dirFile.isDirectory()) {
return false;
}
flag = true;
// 删除文件夹下的所有文件(包括子目录)
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
// 删除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag)
break;
} // 删除子目录
else {
flag = deleteDirectory(files[i].getAbsolutePath());
if (!flag)
break;
}
}
if (!flag)
return false;
// 删除当前目录
if (dirFile.delete()) {
return true;
} else {
return false;
}
}
/**
* 文件转化为字节数组
*
* @EditTime 2007-8-13 上午11:45:28
*/
public static byte[] getBytesFromFile(File f) {
if (f == null) {
return null;
}
try {
FileInputStream stream = new FileInputStream(f);
ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = stream.read(b)) != -1) {
out.write(b, 0, n);
}
stream.close();
out.close();
return out.toByteArray();
} catch (IOException e) {
}
return null;
}
/**
* 把字节数组保存为一个文件
*
* @EditTime 2007-8-13 上午11:45:56
*/
public static File getFileFromBytes(byte[] b, String outputFile) {
BufferedOutputStream stream = null;
File file = null;
try {
file = new File(outputFile);
FileOutputStream fstream = new FileOutputStream(file);
stream = new BufferedOutputStream(fstream);
stream.write(b);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return file;
}
/**
*
* 方法名: </br>
* 详述: <备份数据库/br>
* 创建时间:2015-10-26</br>
*/
public static void backupDB(Context mContext) {
try {
File backup = new File(SDPATH + DBName);
File dbFile = mContext.getDatabasePath(DBPATH);
backup.createNewFile();
fileCopy(dbFile, backup);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* 方法名: </br>
* 详述: </br>
* 创建时间:2015-10-26</br>
*
* @param dbFile
* @param backup
* @throws IOException
*/
public static void fileCopy(File dbFile, File backup) throws IOException {
FileChannel inChannel = new FileInputStream(dbFile).getChannel();
FileChannel outChannel = new FileOutputStream(backup).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inChannel != null) {
inChannel.close();
}
if (outChannel != null) {
outChannel.close();
}
}
}
/**
* @see {@link #assetToFile(Context context, String assetName, File file)}
*/
public static int assetToFile(Context context, String assetName, String path) {
return assetToFile(context, assetName, new File(path));
}
/**
* assets 目录下的文件保存到本地文件
*
* @param context
* @param assetName
* assets下名字,非根目录需包含路径 a/b.xxx
* @param file
* 目标文件
*
* @return 成功 {@link #SUCCESS}; 失败 {@link #FAILED}
*/
public static int assetToFile(Context context, String assetName, File file) {
InputStream is = null;
try {
is = context.getAssets().open(assetName);
return streamToFile(file, is, false);
} catch (Exception e) {
} finally {
try {
is.close();
} catch (Exception e) {
}
}
return FAILED;
}
/**
* 将一缓冲流写入文件
*
* @param path
* 目标文件路径
* @param is
* 输入流
* @param isAppend
* 是否追加
*
* @return 成功 {@link #SUCCESS}; 失败 {@link #FAILED}
*/
public static int streamToFile(String path, InputStream is, boolean isAppend) {
return streamToFile(new File(path), is, isAppend);
}
public static int streamToFile(File file, InputStream is, boolean isAppend) {
checkParentPath(file);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file, isAppend);
byte[] buf = new byte[BUF_SIZE];
int readSize = 0;
while ((readSize = is.read(buf)) != -1)
fos.write(buf, 0, readSize);
fos.flush();
return SUCCESS;
} catch (Exception e) {
} finally {
try {
fos.close();
} catch (Exception e) {
}
}
return FAILED;
}
/**
* @see {@link #checkParentPath(File)}
*/
public static void checkParentPath(String path) {
checkParentPath(new File(path));
}
/**
* 在打开一个文件写数据之前,先检测该文件路径的父目录是否已创建,保证能创建文件
*
* @param file
*/
public static void checkParentPath(File file) {
File parent = file.getParentFile();
if (parent != null && !parent.isDirectory())
createDir(parent);
}
/**
* 创建文件夹
*
* @param path
* @return
*/
public static int createDir(String path) {
return createDir(new File(path));
}
public static int createDir(File file) {
if (file.exists()) {
if (file.isDirectory())
return SUCCESS;
file.delete(); // 避免他是一个文件存在
}
if (file.mkdirs())
return SUCCESS;
return FAILED;
}
}
3.图片处理工具类
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
public class XUtils {
// 照片文件是否存在,注意,与数据库是否存在是不同的
public static Boolean fileExists(String vPath) {
if (null == vPath || "".equals(vPath)) {
return false;
}
try {
File file = new File(vPath);
if (!file.exists()) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
public static int calculateInSampleSize(Options options, int maxWidth, int maxHeight) {
/*
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (width > maxWidth || height > maxHeight) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) maxHeight);
} else {
inSampleSize = Math.round((float) width / (float) maxWidth);
}
final float totalPixels = width * height;
final float maxTotalPixels = maxWidth * maxHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > maxTotalPixels) {
inSampleSize *= 2;
}
}
return inSampleSize;
*/
int inSampleSize;
final int height = options.outHeight;
final int width = options.outWidth;
int minhw;
if(height < width)
minhw = height;
else
minhw = width;
if(minhw < maxWidth)
inSampleSize = 1;
else
{
inSampleSize = Math.round((float) width / (float) maxWidth);
while (minhw / inSampleSize > maxWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
// 获取图片的缩略图, 确保宽度和高度最小的都能覆盖到,比如图片是3000*2000,要缩放到 200*200, 那么缩放后是300*200;
public static Bitmap getThumbImg(String vPath, int vWidth, int vHeight) {
Log.v("getThumbImg", "1==================================");
if (null == vPath) {
Log.v("getThumbImg", "路径为null");
return null;
}
if (vPath.trim().equals("")) {
Log.v("getThumbImg", "路径为空");
return null;
}
Log.v("getThumbImg", "path=" + vPath + ", 期望:width=" + vWidth + ",vheight=" + vHeight);
File file = new File(vPath);
// 如果不存在了,直接返回
if (!file.exists()) {
Log.v("getThumbImg", "文件不存在:path=" + vPath);
return null;
}
// 先获取图片的宽和高
Options options = new Options();
options.inJustDecodeBounds = true;
options.inDither = false; /* 不进行图片抖动处理 */
options.inPreferredConfig = null; /* 设置让解码器以最佳方式解码 */
/* 下面两个字段需要组合使用 */
// options.inPurgeable = true;
// options.inInputShareable = true;
BitmapFactory.decodeFile(vPath, options);
if (options.outWidth <= 0 || options.outHeight <= 0) {
Log.v("getThumbImg", "解析图片失败");
return null;
}
Log.v("getThumbImg", "wid1:" + options.outWidth + ",height:" + options.outHeight + ",path=" + vPath);
int height0 = options.outHeight;
// 压缩图片,注意inSampleSize只能是2的整数次幂,如果不是的,话,向下取最近的2的整数次幂,例如3实际上会是2,7实际上会是4
options.inSampleSize = calculateInSampleSize(options, vWidth, vHeight);
Log.v("getThumbImg", "options.inSampleSize=" + options.inSampleSize);
// 不能用Config.RGB_565
options.inJustDecodeBounds = false;
Bitmap thumbImgNow = null;
try {
thumbImgNow = BitmapFactory.decodeFile(vPath, options);
} catch (OutOfMemoryError e) {
Log.v("getThumbImg", "OutOfMemoryError, decodeFile失败 XXXXXXXXXXXXXXXXXXXXXXXXXXX ");
return null;
}
if (null == thumbImgNow) {
Log.v("getThumbImg", "decodeFile失败 XXXXXXXXXXXXXXXXXXXXXXXXXXX ");
return null;
}
int wid = thumbImgNow.getWidth();
int hgt = thumbImgNow.getHeight();
Log.v("getThumbImg", "1, wid=" + wid + ",hgt=" + hgt);
int degree = readPictureDegree(vPath);
if (degree != 0) {
Log.v("getThumbImg", "degree=" + degree);
// 把图片旋转为正的方向
thumbImgNow = rotateImage(degree, thumbImgNow);
}
return thumbImgNow;
}
/**
* 旋转图片
*
* @param angle
* @param bitmap
* @return Bitmap
*/
public static Bitmap rotateImage(int angle, Bitmap bitmap) {
if (null == bitmap) {
return bitmap;
}
// 图片旋转矩阵
Matrix matrix = new Matrix();
matrix.postRotate(angle);
if (null == bitmap) {
Log.v("rotateImageError", "bitmap is null");
return bitmap;
}
// 得到旋转后的图片
try {
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap;
} catch (OutOfMemoryError e) {
return bitmap;
}
}
/**
* 读取图片属性:旋转的角度
*
* @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;
}
public static Boolean saveByteToFile(byte[] vData, String vFilePath) {
Log.v("saveByteToFile", "1");
if (null == vData || TextUtils.isEmpty(vFilePath)) {
Log.v("saveByteToFile", "vData or filepath is error");
return false;
}
Log.v("saveByteToFile", "vData.len=" + vData.length);
Log.v("saveByteToFile", "vFilePath=" + vFilePath);
File tFile = new File(vFilePath);
if (null == tFile) {
Log.v("saveByteToFile", "new file failed ");
return false;
}
try {
FileOutputStream fos = new FileOutputStream(tFile);
try {
fos.write(vData);
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
}
Log.v("saveByteToFile", "success");
return true;
}
public static byte[] loadByteFromFile(String vFilePath, int vLen) {
Log.v("loadByteFromFile", "1");
if (TextUtils.isEmpty(vFilePath) || vLen < 1) {
return null;
}
File tFile = new File(vFilePath);
if (null == tFile) {
Log.v("loadByteFromFile", "new file failed ");
return null;
}
byte tByte[] = new byte[vLen];
FileInputStream fin = null;
try {
fin = new FileInputStream(tFile);
int r = fin.read(tByte);
if (r != vLen) {
throw new IOException("Can't read all, " + r + " != " + vLen);
}
} catch (Exception e) {
}
return tByte;
}
public static Boolean saveBitmap(Bitmap vBmp, String vPath) {
Log.v("saveBitmap", "1");
if (null == vBmp) {
Log.v("saveBitmap", "(null == vBmp)");
return false;
}
if (vBmp.isRecycled()) {
Log.e("saveBitmap", "已被回收");
return false;
}
if (vBmp.getWidth() < 1) {
Log.e("saveBitmap", "图像宽度<1");
return false;
}
if (null == vPath || vPath.trim().equals("")) {
Log.e("saveBitmap", "(null == vPath)");
return false;
}
int tPos = vPath.lastIndexOf("/");
String tDir = tPos >= 0 ? vPath.substring(0, tPos) : vPath;
Log.v("saveBitmap", "父目录,tDir = " + tDir);
File file = new File(tDir);
// 如果文件夹不存在则创建
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
Log.v("saveBitmap", "vPath = " + vPath);
try {
FileOutputStream fout = new FileOutputStream(vPath);
BufferedOutputStream bos = new BufferedOutputStream(fout);
vBmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
Log.v("saveBitmap", "保存成功");
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("saveBitmap", "保存失败," + e.toString());
e.printStackTrace();
return false;
}
}
// 整数数组转字符串
public static String intArrayToString(int[] vArr) {
String tRetString = "";
if (null == vArr || vArr.length < 1) {
return tRetString;
}
int num = vArr.length;
for (int i = 0; i < num; i++) {
tRetString += vArr[i] + ",";
}
if (!TextUtils.isEmpty(tRetString)) {
tRetString = tRetString.substring(0, tRetString.length() - 1);
}
return tRetString;
}
/**
* 根据图像完整路径判断是否图像文件
*
* @param
* @return
*/
private boolean isImageFile(String vPath) {
if (null == vPath || vPath.trim().length() < 1) {
return false;
}
String tPath = vPath.trim();
// 检查后缀名
String end = tPath.substring(tPath.lastIndexOf(".") + 1, tPath.length()).toLowerCase();
if ("".equals(end.trim())) {
return false;
}
// 依据文件扩展名判断是否为图像文件
if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")
|| end.equals("mov")) {
} else {
return false;
}
// 判断文件是否存在
File file = new File(tPath);
if (!file.exists()) {
return false;
}
return true;
}
// 判断网络是否连接
public static Boolean isNetworkConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
}
return false;
}
// 把逗号、分号等符号分隔的字符串转换为double数组
public static String[] stringStringValueSplit(String vStr) {
Log.v("stringStringValueSplit", "1");
if (TextUtils.isEmpty(vStr)) {
return null;
}
Log.v("stringStringValueSplit", vStr);
String oldString = vStr;
vStr = vStr.replaceAll("\\r", "");
vStr = vStr.replaceAll("\\n", "");
vStr = vStr.replaceAll("\\[", "");
vStr = vStr.replaceAll("\\]", "");
vStr = vStr.replaceAll(";", ",");
vStr = vStr.replaceAll(" ", "");
Log.v("stringStringValueSplit", "str after replace =" + vStr + ", old=" + oldString);
return vStr.split(",|;|\\[|\\]");
}
// 把逗号、分号等符号分隔的字符串转换为double数组
public static int[] stringIntValueSplit(String vStr) {
Log.v("stringIntValueSplit", "1");
if (TextUtils.isEmpty(vStr)) {
return null;
}
Log.v("stringIntValueSplit", vStr);
String oldString = vStr;
vStr = vStr.replaceAll("\\r", "");
vStr = vStr.replaceAll("\\n", "");
vStr = vStr.replaceAll("\\[", "");
vStr = vStr.replaceAll("\\]", "");
vStr = vStr.replaceAll(";", ",");
vStr = vStr.replaceAll(" ", "");
Log.v("stringIntValueSplit", "str after replace =" + vStr + ", old=" + oldString);
String[] pStr = vStr.split(",|;|\\[|\\]");
if (null == pStr || 0 == pStr.length) {
Log.v("stringIntValueSplit", "pStr.length=0");
return null;
}
int[] dRet = new int[pStr.length];
Log.v("stringIntValueSplit", "pStr.length=" + pStr.length);
for (int i = 0; i < pStr.length; i++) {
String tString = pStr[i];
if (null == tString || tString.trim().equals("")) {
Log.v("stringIntValueSplit", "i=" + i + ", null, or '' ");
continue;
}
try {
dRet[i] = Integer.parseInt(tString);
} catch (NumberFormatException ex) {
// System.out.println("The String does not contain a parsable integer");
Log.v("stringIntValueSplit", "NumberFormatException," + ex.toString());
}
}
return dRet;
}
public static long getmem_UNUSED(Context mContext) {
long MEM_UNUSED;
// 得到ActivityManager
ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
// 创建ActivityManager.MemoryInfo对象
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
am.getMemoryInfo(mi);
// 取得剩余的内存空间
MEM_UNUSED = mi.availMem / 1024;
return MEM_UNUSED;
}
// android sdk 中的Bitmap类提供了一个实例方法copy用来复制位图,该方法在复制较大图像时
//
// 容易造成内存溢出;原因:该方法在复制图像时将在内存中保存两份图像数据。
//
// 为了解决这个问题,可以将大图像写入SD卡中的一个临时文件中,然后再从文件中取出图像。
//
// 根据以上思路用代码如下:
/**
* 根据原位图生成一个新的位图,并将原位图所占空间释放
*
* @param srcBmp
* 原位图
* @return 新位图
*/
public static Bitmap bmpcopy(Bitmap srcBmp) {
Bitmap destBmp = null;
try {
// 创建一个临时文件
File file = new File("/mnt/sdcard/tempbmp/tmp.txt");
file.getParentFile().mkdirs();
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
int width = srcBmp.getWidth();
int height = srcBmp.getHeight();
FileChannel channel = randomAccessFile.getChannel();
MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, width * height * 4);
// 将位图信息写进buffer
srcBmp.copyPixelsToBuffer(map);
// 释放原位图占用的空间
srcBmp.recycle();
// 创建一个新的位图
destBmp = Bitmap.createBitmap(width, height, Config.ARGB_8888);
map.position(0);
// 从临时缓冲中拷贝位图信息
destBmp.copyPixelsFromBuffer(map);
channel.close();
randomAccessFile.close();
} catch (Exception ex) {
destBmp = null;
}
return destBmp;
}
/**
*
* 方法名: </br>
* 详述:取识别人脸截图 </br>
* 创建时间:2015年12月10日</br>
*
* @param
* @param
* @return
*/
/*
public static Bitmap getScaledBitmap(String vPath, int vWidth, int vHeight) {
Log.v("getThumbImg", "1==================================");
if (null == vPath) {
Log.v("getThumbImg", "路径为null");
return null;
}
if (vPath.trim().equals("")) {
Log.v("getThumbImg", "路径为空");
return null;
}
Log.v("getThumbImg", "path=" + vPath + ", 期望:width=" + vWidth + ",vheight=" + vHeight);
File file = new File(vPath);
// 如果不存在了,直接返回
if (!file.exists()) {
Log.v("getThumbImg", "文件不存在:path=" + vPath);
return null;
}
// 先获取图片的宽和高
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(vPath, options);
if (options.outWidth <= 0 || options.outHeight <= 0) {
Log.v("getThumbImg", "解析图片失败");
return null;
}
Log.v("getThumbImg", "wid1:" + options.outWidth + ",height:" + options.outHeight + ",path=" + vPath);
int height0 = options.outHeight;
// 压缩图片,注意inSampleSize只能是2的整数次幂,如果不是的,话,向下取最近的2的整数次幂,例如3实际上会是2,7实际上会是4
options.inSampleSize = calculateInSampleSize(options, vWidth, vHeight);
Log.v("getThumbImg", "options.inSampleSize=" + options.inSampleSize);
// 不能用Config.RGB_565
options.inJustDecodeBounds = false;
Bitmap thumbImgNow = null;
try {
thumbImgNow = BitmapFactory.decodeFile(vPath, options);
} catch (OutOfMemoryError e) {
Log.v("getThumbImg", "OutOfMemoryError, decodeFile失败 XXXXXXXXXXXXXXXXXXXXXXXXXXX ");
return null;
}
//Bitmap.createScaledBitmap(src, dstWidth, dstHeight, filter)
if (null == thumbImgNow) {
Log.v("getThumbImg", "decodeFile失败 XXXXXXXXXXXXXXXXXXXXXXXXXXX ");
return null;
}
int wid = thumbImgNow.getWidth();
int hgt = thumbImgNow.getHeight();
Log.v("getThumbImg", "1, wid=" + wid + ",hgt=" + hgt);
int degree = readPictureDegree(vPath);
if (degree != 0) {
Log.v("getThumbImg", "degree=" + degree);
// 把图片旋转为正的方向
thumbImgNow = rotateImage(degree, thumbImgNow);
}
return thumbImgNow;
}
*/
//获取图片的缩略图,宽度和高度中较小的缩放到vMinWidth. 确保宽度和高度最小的都能覆盖到,
//比如图片是3000*2000,要缩放到 150*100, 那么vMinWidth=100;
public static Bitmap getScaledBitmap(String vPath, int vMinWidth) {
String tag = "getScaledBitmap";
Log.v(tag, "1==");
if(null == vPath){
Log.v(tag, "路径为null");
return null;
}
if(vPath.trim().equals("")){
Log.v(tag, "路径为空");
return null;
}
Log.v(tag, "path="+vPath+", 期望:vMinWidth="+vMinWidth);
File file = new File(vPath);
//如果不存在了,直接返回
if(!file.exists()){
Log.v(tag, "文件不存在:path="+vPath);
return null;
}
// 先获取图片的宽和高
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(vPath, options);
if (options.outWidth <= 0 || options.outHeight <= 0) {
Log.v(tag, "解析图片失败");
return null;
}
Log.v(tag, "原图大小:width:" + options.outWidth + ",height:"
+ options.outHeight + ",path=" + vPath);
int height0 = options.outHeight;
int tMinWidth = Math.min(options.outWidth, options.outHeight);
// 压缩图片,注意inSampleSize只能是2的整数次幂,如果不是的,话,向下取最近的2的整数次幂,例如3实际上会是2,7实际上会是4
options.inSampleSize = Math.max(1, tMinWidth/vMinWidth);
//Log.v(tag, "options.inSampleSize="+options.inSampleSize);
//不能用Config.RGB_565
//options.inPreferredConfig = Config.RGB_565;
// options.inDither = false;
// options.inPurgeable = true;
// options.inInputShareable = true;
options.inJustDecodeBounds = false;
Bitmap thumbImgNow = null;
try{
thumbImgNow = BitmapFactory.decodeFile(vPath, options);
}catch(OutOfMemoryError e){
Log.v(tag, "OutOfMemoryError, decodeFile失败 ");
return null;
}
//Log.v(tag, "thumbImgNow.size="+thumbImgNow.getWidth()+","+thumbImgNow.getHeight());
if(null == thumbImgNow){
Log.v(tag, "decodeFile失败 ");
return null;
}
int wid = thumbImgNow.getWidth();
int hgt = thumbImgNow.getHeight();
int degree = readPictureDegree(vPath);
if (degree != 0) {
//Log.v(tag, "degree="+degree);
// 把图片旋转为正的方向
thumbImgNow = rotateImage(degree, thumbImgNow);
}
wid = thumbImgNow.getWidth();
hgt = thumbImgNow.getHeight();
tMinWidth = Math.min(wid, hgt);
if (tMinWidth > vMinWidth) {
//如果原图片最小宽度比预期最小高度大才进行缩小
float ratio = ((float) vMinWidth) / tMinWidth;
Matrix matrix = new Matrix();
matrix.postScale(ratio, ratio);
thumbImgNow = Bitmap.createBitmap(thumbImgNow, 0, 0, wid, hgt, matrix, true);
}
Log.v(tag, "处理后, size, width="+thumbImgNow.getWidth()+",height="+thumbImgNow.getHeight());
return thumbImgNow;
}
}