1.跟app相关的辅助类
package com.example.coshenwancheng.utils; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; /** * 跟App相关的辅助类 * * * */ public class AppUtils { private AppUtils() { /**cannot be instantiated **/ throw new UnsupportedOperationException("cannot be instantiated"); } /** * 获取应用程序名称 */ public static String getAppName(Context context) { try { PackageManager packageManager = context.getPackageManager(); PackageInfo packageInfo = packageManager.getPackageInfo( context.getPackageName(), 0); int labelRes = packageInfo.applicationInfo.labelRes; return context.getResources().getString(labelRes); } catch (NameNotFoundException e) { e.printStackTrace(); } return null; } /** * [获取应用程序版本名称信息] * * @param context * @return 当前应用的版本名称 */ public static String getVersionName(Context context) { try { PackageManager packageManager = context.getPackageManager(); PackageInfo packageInfo = packageManager.getPackageInfo( context.getPackageName(), 0); return packageInfo.versionName; } catch (NameNotFoundException e) { e.printStackTrace(); } return null; } }
2.Assets获取的相关操作类
package com.example.coshenwancheng.utils; import android.content.Context; import android.content.res.AssetManager; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; /** * @desc: Assets获取的相关操作类 */ public class AssetsUtils { private static final String ENCODING = "UTF-8"; /** * 从assets获取文件 * * @param context * @param fileName * @return * @throws IOException */ public static InputStream getFileFromAssets(Context context, String fileName) throws IOException { AssetManager am = context.getAssets(); return am.open(fileName); } /** * 从assets获取文本文件 * * @param context * @param fileName * @return */ public static String getTextFromAssets(Context context, String fileName) { String result = null; try { InputStream in = getFileFromAssets(context, fileName); int length = in.available(); byte[] buffer = new byte[length]; in.read(buffer); result = new String(buffer, Charset.forName(ENCODING)); } catch (IOException e) { e.printStackTrace(); } return result; } /** * 从assets获取文本文件 * * @param context * @param fileName * @return */ public static String getTextFromAssets2(Context context, String fileName) { try { InputStreamReader inputReader = new InputStreamReader(getFileFromAssets(context, fileName)); BufferedReader bufReader = new BufferedReader(inputReader); String line = ""; StringBuilder result = new StringBuilder(); while ((line = bufReader.readLine()) != null) { result.append(line); } return result.toString(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * Parse a json file in the assets to ArrayList<?> * 解析json文件成ArrayList,在assets中 * @param context * @param jsonName * @return */ public static <T> ArrayList<T> parseJsonToArrayList(Context context, String jsonName) { String json = getTextFromAssets(context, jsonName); return JsonUtils.jsonToArrayList(json); } /** * Parse a json file in the assets to List<?> * 解析json文件成List,在assets中 * @param context * @param jsonName * @return */ public static <T> List<T> parseJsonToList(Context context, String jsonName) { String json = getTextFromAssets(context, jsonName); return JsonUtils.jsonToList(json); } /** * Parse a json file in the assets to Bean * 解析assets中的json文件 * @param context * @param jsonName * @param clazz * @return */ public static <T> T parseJsonToObject(Context context, String jsonName, Class<T> clazz) { String json = getTextFromAssets(context, jsonName); return JsonUtils.jsonToObject(json, clazz); } }
3.base64的转换
package com.example.coshenwancheng.utils; import android.util.Base64; /** * @desc: bese64的转换 */ public class BASE64Utils { /** * base64编码 * * @param input * @return */ public static byte[] encodeBase64(byte[] input) { return Base64.encode(input, Base64.DEFAULT); } /** * base64编码 * * @param s * @return */ public static String encodeBase64(String s) { return Base64.encodeToString(s.getBytes(), Base64.DEFAULT); } /** * base64解码 * * @param input * @return */ public static byte[] decodeBase64(byte[] input) { return Base64.decode(input, Base64.DEFAULT); } /** * base64解码 * * @param s * @return */ public static String decodeBase64(String s) { return new String(Base64.decode(s, Base64.DEFAULT)); } }
4.bitmap图片的相互转换工具类
package com.example.coshenwancheng.utils; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PaintFlagsDrawFilter; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.media.ExifInterface; import android.os.Build; import android.view.View; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * @desc: bitmap图片的相互转换工具类 */ public class BitmapUtils { public static final int UNSPECIFIED = 0; /** * Convert resId to drawable * * @param context * @param resId * @return */ public static Drawable resToDrawable(Context context, int resId) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return context.getDrawable(resId); } return context.getResources().getDrawable(resId); } /** * Convert Bitmap to byte array * * @param b * @return */ public static byte[] bitmapToByte(Bitmap b) { if (b == null) { return null; } ByteArrayOutputStream o = new ByteArrayOutputStream(); b.compress(Bitmap.CompressFormat.PNG, 100, o); return o.toByteArray(); } /** * Convert byte array to Bitmap * * @param b * @return */ public static Bitmap byteToBitmap(byte[] b) { return (b == null || b.length == 0) ? null : BitmapFactory.decodeByteArray(b, 0, b.length); } /** * Convert Drawable to Bitmap * * @param d * @return */ public static Bitmap drawableToBitmap(Drawable d) { return d == null ? null : ((BitmapDrawable) d).getBitmap(); } /** * Convert Bitmap to Drawable * * @param b * @return */ public static Drawable bitmapToDrawable(Bitmap b) { return b == null ? null : new BitmapDrawable(b); } /** * Convert Drawable to byte array * * @param d * @return */ public static byte[] drawableToByte(Drawable d) { return bitmapToByte(drawableToBitmap(d)); } /** * Convert byte array to Drawable * * @param b * @return */ public static Drawable byteToDrawable(byte[] b) { return bitmapToDrawable(byteToBitmap(b)); } /** * Convert view to bitmap * * @param view * @param width * @param height * @return */ public static Bitmap convertViewToBitmap(View view, int width, int height) { view.measure(View.MeasureSpec.makeMeasureSpec(width, (width == UNSPECIFIED) ? View.MeasureSpec.UNSPECIFIED : View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(height, (height == UNSPECIFIED) ? View.MeasureSpec.UNSPECIFIED : View.MeasureSpec.EXACTLY)); view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888); view.draw(new Canvas(bitmap)); return bitmap; } /** * Convert view to bitmap * * @param view * @return */ public static Bitmap convertViewToBitmap(View view) { return convertViewToBitmap(view, UNSPECIFIED, UNSPECIFIED); } /** * Resize image by width and height * * @param originalBitmap * @param w * @param h * @return */ public static Bitmap resizeImage(Bitmap originalBitmap, int w, int h) { if (originalBitmap == null) { return null; } int width = originalBitmap.getWidth(); int height = originalBitmap.getHeight(); if (width <= w && height <= h) { return originalBitmap; } float screenRatio = (float) w / h; float ratio = (float) width / height; if (screenRatio >= ratio) { width = (int) (h * ratio); height = h; } else { height = (int) (w / ratio); width = w; } return Bitmap.createScaledBitmap(originalBitmap, width, height, true); } /** * Decode bitmap * * @param is * @param context * @return * @throws IOException */ public static Bitmap decodeBitmap(InputStream is, Context context) throws IOException { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; // 设置成了true,不占用内存,只获取bitmap宽高 byte[] data = isToByte(is);//将InputStream转为byte数组,可以多次读取 // BitmapFactory.decodeStream(is, null, options);InputStream流只能被读取一次,下次读取就为空了。 BitmapFactory.decodeByteArray(data, 0, data.length, options); options.inSampleSize = calculateInSampleSize(options, context); // 调用上面定义的方法计算inSampleSize值 // 使用获取到的inSampleSize值再次解析图片 options.inJustDecodeBounds = false; return BitmapFactory.decodeByteArray(data, 0, data.length, options); } /** * Calculate inSampleSize * * @param options * @param context * @return */ private static int calculateInSampleSize(BitmapFactory.Options options, Context context) { // 源图片的高度和宽度 final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; int h = DisplayUtils.getScreenHeight(context); int w = DisplayUtils.getScreenWidth(context); if (height > h || width > w) { // 计算出实际宽高和目标宽高的比率 final int heightRatio = Math.round((float) height / (float) h); final int widthRatio = Math.round((float) width / (float) w); // 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高 // 一定都会大于等于目标的宽和高。 inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } /** * Convert InputStream to byte array * * @param is * @return * @throws IOException */ private static byte[] isToByte(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; int len = 0; while ((len = is.read(buff)) != -1) { baos.write(buff, 0, len); } is.close(); baos.close(); return baos.toByteArray(); } /** * take a screenshot * * @param activity * @param filePath * @return */ public static boolean screenshot(Activity activity, String filePath) { View decorView = activity.getWindow().getDecorView(); decorView.setDrawingCacheEnabled(true); decorView.buildDrawingCache(); Bitmap bitmap = decorView.getDrawingCache(); File imagePath = new File(filePath); FileOutputStream fos = null; try { fos = new FileOutputStream(imagePath); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); return true; } catch (Exception e) { e.printStackTrace(); } finally { try { fos.close(); if (null != bitmap) { bitmap.recycle(); bitmap = null; } } catch (Exception e) { } decorView.destroyDrawingCache(); decorView.setDrawingCacheEnabled(false); } return false; } /** * Combine bitmaps * * @param bgBitmap 背景Bitmap * @param fgBitmap 前景Bitmap * @return 合成后的Bitmap */ public static Bitmap combineBitmap(Bitmap bgBitmap, Bitmap fgBitmap) { Bitmap bmp; int width = bgBitmap.getWidth() > fgBitmap.getWidth() ? bgBitmap.getWidth() : fgBitmap .getWidth(); int height = bgBitmap.getHeight() > fgBitmap.getHeight() ? bgBitmap.getHeight() : fgBitmap .getHeight(); bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Paint paint = new Paint(); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); Canvas canvas = new Canvas(bmp); canvas.drawBitmap(bgBitmap, 0, 0, null); canvas.drawBitmap(fgBitmap, 0, 0, paint); return bmp; } /** * Combine bitmaps * * @param bgd 后景Bitmap * @param fg 前景Bitmap * @return 合成后Bitmap */ public static Bitmap combineBitmapInSameSize(Bitmap bgd, Bitmap fg) { Bitmap bmp; int width = bgd.getWidth() < fg.getWidth() ? bgd.getWidth() : fg .getWidth(); int height = bgd.getHeight() < fg.getHeight() ? bgd.getHeight() : fg .getHeight(); if (fg.getWidth() != width && fg.getHeight() != height) { fg = zoom(fg, width, height); } if (bgd.getWidth() != width && bgd.getHeight() != height) { bgd = zoom(bgd, width, height); } bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Paint paint = new Paint(); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); Canvas canvas = new Canvas(bmp); canvas.drawBitmap(bgd, 0, 0, null); canvas.drawBitmap(fg, 0, 0, paint); return bmp; } /** * zoom bitmap * * @param bitmap 源Bitmap * @param w 宽 * @param h 高 * @return 目标Bitmap */ public static Bitmap zoom(Bitmap bitmap, int w, int h) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); Matrix matrix = new Matrix(); float scaleWidht = ((float) w / width); float scaleHeight = ((float) h / height); matrix.postScale(scaleWidht, scaleHeight); Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); return newbmp; } /** * Get rounded corner bitmap * * @param bitmap * @param roundPx 圆角大小 * @return */ public static Bitmap createRoundedCornerBitmap(Bitmap bitmap, float roundPx) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } /** * Get reflection bitmap * * @param bitmap 源Bitmap * @return 带倒影的Bitmap */ public static Bitmap createReflectionBitmap(Bitmap bitmap) { final int reflectionGap = 4; int width = bitmap.getWidth(); int height = bitmap.getHeight(); Matrix matrix = new Matrix(); matrix.preScale(1, -1); Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2, width, height / 2, matrix, false); Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmapWithReflection); canvas.drawBitmap(bitmap, 0, 0, null); Paint deafalutPaint = new Paint(); canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint); canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); Paint paint = new Paint(); LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, Shader.TileMode.CLAMP); paint.setShader(shader); // Set the Transfer mode to be porter duff and destination in paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); // Draw a rectangle using the paint with our linear gradient canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint); return bitmapWithReflection; } /** * Compress bitmap * * @param bmp 源Bitmap * @return 压缩后的Bitmap */ public static Bitmap compressBitmap(Bitmap bmp) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 int options = 100; while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩 baos.reset();// 重置baos即清空baos bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中 options -= 10;// 每次都减少10 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片 return bitmap; } /** * 将彩色图转换为灰度图 * * @param img 源Bitmap * @return 返回转换好的位图 */ public static Bitmap convertGreyImg(Bitmap img) { int width = img.getWidth(); // 获取位图的宽 int height = img.getHeight(); // 获取位图的高 int[] pixels = new int[width * height]; // 通过位图的大小创建像素点数组 img.getPixels(pixels, 0, width, 0, 0, width, height); int alpha = 0xFF << 24; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int grey = pixels[width * i + j]; int red = ((grey & 0x00FF0000) >> 16); int green = ((grey & 0x0000FF00) >> 8); int blue = (grey & 0x000000FF); grey = (int) ((float) red * 0.3 + (float) green * 0.59 + (float) blue * 0.11); grey = alpha | (grey << 16) | (grey << 8) | grey; pixels[width * i + j] = grey; } } Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); result.setPixels(pixels, 0, width, 0, 0, width, height); return result; } /** * Get round bitmap * * @param bitmap * @return */ public static Bitmap createRoundBitmap(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); float roundPx; float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom; if (width <= height) { roundPx = width / 2; top = 0; bottom = width; left = 0; right = width; height = width; dst_left = 0; dst_top = 0; dst_right = width; dst_bottom = width; } else { roundPx = height / 2; float clip = (width - height) / 2; left = clip; right = width - clip; top = 0; bottom = height; width = height; dst_left = 0; dst_top = 0; dst_right = height; dst_bottom = height; } Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom); final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom); final RectF rectF = new RectF(dst); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, src, dst, paint); return output; } /** * Returns a Bitmap representing the thumbnail of the specified Bitmap. * * @param bitmap * @param context * @return */ public static Bitmap createThumbnailBitmap(Bitmap bitmap, Context context) { int sIconWidth = -1; int sIconHeight = -1; final Resources resources = context.getResources(); sIconWidth = sIconHeight = (int) resources .getDimension(android.R.dimen.app_icon_size); final Paint sPaint = new Paint(); final Rect sBounds = new Rect(); final Rect sOldBounds = new Rect(); Canvas sCanvas = new Canvas(); int width = sIconWidth; int height = sIconHeight; sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG, Paint.FILTER_BITMAP_FLAG)); final int bitmapWidth = bitmap.getWidth(); final int bitmapHeight = bitmap.getHeight(); if (width > 0 && height > 0) { if (width < bitmapWidth || height < bitmapHeight) { final float ratio = (float) bitmapWidth / bitmapHeight; if (bitmapWidth > bitmapHeight) { height = (int) (width / ratio); } else if (bitmapHeight > bitmapWidth) { width = (int) (height * ratio); } final Bitmap.Config c = (width == sIconWidth && height == sIconHeight) ? bitmap .getConfig() : Bitmap.Config.ARGB_8888; final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c); final Canvas canvas = sCanvas; final Paint paint = sPaint; canvas.setBitmap(thumb); paint.setDither(false); paint.setFilterBitmap(true); sBounds.set((sIconWidth - width) / 2, (sIconHeight - height) / 2, width, height); sOldBounds.set(0, 0, bitmapWidth, bitmapHeight); canvas.drawBitmap(bitmap, sOldBounds, sBounds, paint); return thumb; } else if (bitmapWidth < width || bitmapHeight < height) { final Bitmap.Config c = Bitmap.Config.ARGB_8888; final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c); final Canvas canvas = sCanvas; final Paint paint = sPaint; canvas.setBitmap(thumb); paint.setDither(false); paint.setFilterBitmap(true); canvas.drawBitmap(bitmap, (sIconWidth - bitmapWidth) / 2, (sIconHeight - bitmapHeight) / 2, paint); return thumb; } } return bitmap; } /** * Create bitmap with watermark, in bottom right corner. * * @param src * @param watermark * @return */ public static Bitmap createWatermarkBitmap(Bitmap src, Bitmap watermark) { if (src == null) { return null; } int w = src.getWidth(); int h = src.getHeight(); int ww = watermark.getWidth(); int wh = watermark.getHeight(); // create the new blank bitmap // 创建一个新的和SRC长度宽度一样的位图 Bitmap newb = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas cv = new Canvas(newb); // draw src into // 在 0,0坐标开始画入src cv.drawBitmap(src, 0, 0, null); // draw watermark into // 在src的右下角画入水印 cv.drawBitmap(watermark, w - ww + 5, h - wh + 5, null); // save all clip // 保存 cv.save(Canvas.ALL_SAVE_FLAG); // store cv.restore();// 存储 return newb; } /** * 重新编码Bitmap * * @param src 需要重新编码的Bitmap * @param format 编码后的格式(目前只支持png和jpeg这两种格式) * @param quality 重新生成后的bitmap的质量 * @return 返回重新生成后的bitmap */ public static Bitmap decodeBitmap(Bitmap src, Bitmap.CompressFormat format, int quality) { ByteArrayOutputStream os = new ByteArrayOutputStream(); src.compress(format, quality, os); byte[] array = os.toByteArray(); return BitmapFactory.decodeByteArray(array, 0, array.length); } /** * 图片压缩,如果bitmap本身的大小小于maxSize,则不作处理 * * @param bitmap 要压缩的图片 * @param maxSize 压缩后的大小,单位kb */ public static void compressBitmap(Bitmap bitmap, double maxSize) { // 将bitmap放至数组中,意在获得bitmap的大小(与实际读取的原文件要大) ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 格式、质量、输出流 bitmap.compress(Bitmap.CompressFormat.PNG, 70, baos); byte[] b = baos.toByteArray(); // 将字节换成KB double mid = b.length / 1024; // 获取bitmap大小 是允许最大大小的多少倍 double i = mid / maxSize; // 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩 if (i > 1) { // 缩放图片 此处用到平方根 将宽带和高度压缩掉对应的平方根倍 // (保持宽高不变,缩放后也达到了最大占用空间的大小) bitmap = scale(bitmap, bitmap.getWidth() / Math.sqrt(i), bitmap.getHeight() / Math.sqrt(i)); } } /** * scale bitmap * * @param src * @param newWidth * @param newHeight * @return */ public static Bitmap scale(Bitmap src, double newWidth, double newHeight) { // 记录src的宽高 float width = src.getWidth(); float height = src.getHeight(); // 创建一个matrix容器 Matrix matrix = new Matrix(); // 计算缩放比例 float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // 开始缩放 matrix.postScale(scaleWidth, scaleHeight); // 创建缩放后的图片 return Bitmap.createBitmap(src, 0, 0, (int) width, (int) height, matrix, true); } /** * scale bitmap * * @param src * @param scaleMatrix * @return */ public static Bitmap scale(Bitmap src, Matrix scaleMatrix) { return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), scaleMatrix, true); } /** * scale bitmap * * @param src * @param scaleX * @param scaleY * @return */ public static Bitmap scale(Bitmap src, float scaleX, float scaleY) { Matrix matrix = new Matrix(); matrix.postScale(scaleX, scaleY); return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true); } /** * scale bitmap with the same scale * * @param src * @param scale * @return */ public static Bitmap scale(Bitmap src, float scale) { return scale(src, scale, scale); } /** * rotate bitmap * * @param bitmap * @param angle * @return */ public static Bitmap rotate(Bitmap bitmap, int angle) { Matrix matrix = new Matrix(); matrix.postRotate(angle); return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } /** * 水平翻转处理 * * @param bitmap 原图 * @return 水平翻转后的图片 */ public static Bitmap reverseHorizontal(Bitmap bitmap) { Matrix matrix = new Matrix(); matrix.preScale(-1, 1); return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false); } /** * 垂直翻转处理 * * @param bitmap 原图 * @return 垂直翻转后的图片 */ public static Bitmap reverseVertical(Bitmap bitmap) { Matrix matrix = new Matrix(); matrix.preScale(1, -1); return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false); } /** * 更改图片色系,变亮或变暗 * * @param delta 图片的亮暗程度值,越小图片会越亮,取值范围(0,24) * @return */ public static Bitmap adjustTone(Bitmap src, int delta) { if (delta >= 24 || delta <= 0) { return null; } // 设置高斯矩阵 int[] gauss = new int[]{1, 2, 1, 2, 4, 2, 1, 2, 1}; int width = src.getWidth(); int height = src.getHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); int pixR = 0; int pixG = 0; int pixB = 0; int pixColor = 0; int newR = 0; int newG = 0; int newB = 0; int idx = 0; int[] pixels = new int[width * height]; src.getPixels(pixels, 0, width, 0, 0, width, height); for (int i = 1, length = height - 1; i < length; i++) { for (int k = 1, len = width - 1; k < len; k++) { idx = 0; for (int m = -1; m <= 1; m++) { for (int n = -1; n <= 1; n++) { pixColor = pixels[(i + m) * width + k + n]; pixR = Color.red(pixColor); pixG = Color.green(pixColor); pixB = Color.blue(pixColor); newR += (pixR * gauss[idx]); newG += (pixG * gauss[idx]); newB += (pixB * gauss[idx]); idx++; } } newR /= delta; newG /= delta; newB /= delta; newR = Math.min(255, Math.max(0, newR)); newG = Math.min(255, Math.max(0, newG)); newB = Math.min(255, Math.max(0, newB)); pixels[i * width + k] = Color.argb(255, newR, newG, newB); newR = 0; newG = 0; newB = 0; } } bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } /** * 将彩色图转换为黑白图 * * @param bmp 位图 * @return 返回转换好的位图 */ public static Bitmap convertToBlackWhite(Bitmap bmp) { int width = bmp.getWidth(); int height = bmp.getHeight(); int[] pixels = new int[width * height]; bmp.getPixels(pixels, 0, width, 0, 0, width, height); int alpha = 0xFF << 24; // 默认将bitmap当成24色图片 for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int grey = pixels[width * i + j]; int red = ((grey & 0x00FF0000) >> 16); int green = ((grey & 0x0000FF00) >> 8); int blue = (grey & 0x000000FF); grey = (int) (red * 0.3 + green * 0.59 + blue * 0.11); grey = alpha | (grey << 16) | (grey << 8) | grey; pixels[width * i + j] = grey; } } Bitmap newBmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); newBmp.setPixels(pixels, 0, width, 0, 0, width, height); return newBmp; } /** * 读取图片属性:图片被旋转的角度 * * @param path 图片绝对路径 * @return 旋转的角度 */ public static int getImageDegree(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 bitmap 原图 * @param saturationValue 新的饱和度值 * @return 改变了饱和度值之后的图片 */ public static Bitmap saturation(Bitmap bitmap, int saturationValue) { // 计算出符合要求的饱和度值 float newSaturationValue = saturationValue * 1.0F / 127; // 创建一个颜色矩阵 ColorMatrix saturationColorMatrix = new ColorMatrix(); // 设置饱和度值 saturationColorMatrix.setSaturation(newSaturationValue); // 创建一个画笔并设置其颜色过滤器 Paint paint = new Paint(); paint.setColorFilter(new ColorMatrixColorFilter(saturationColorMatrix)); // 创建一个新的图片并创建画布 Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(newBitmap); // 将原图使用给定的画笔画到画布上 canvas.drawBitmap(bitmap, 0, 0, paint); return newBitmap; } /** * 亮度处理 * * @param bitmap 原图 * @param lumValue 新的亮度值 * @return 改变了亮度值之后的图片 */ public static Bitmap lum(Bitmap bitmap, int lumValue) { // 计算出符合要求的亮度值 float newlumValue = lumValue * 1.0F / 127; // 创建一个颜色矩阵 ColorMatrix lumColorMatrix = new ColorMatrix(); // 设置亮度值 lumColorMatrix.setScale(newlumValue, newlumValue, newlumValue, 1); // 创建一个画笔并设置其颜色过滤器 Paint paint = new Paint(); paint.setColorFilter(new ColorMatrixColorFilter(lumColorMatrix)); // 创建一个新的图片并创建画布 Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(newBitmap); // 将原图使用给定的画笔画到画布上 canvas.drawBitmap(bitmap, 0, 0, paint); return newBitmap; } /** * 色相处理 * * @param bitmap 原图 * @param hueValue 新的色相值 * @return 改变了色相值之后的图片 */ public static Bitmap hue(Bitmap bitmap, int hueValue) { // 计算出符合要求的色相值 float newHueValue = (hueValue - 127) * 1.0F / 127 * 180; // 创建一个颜色矩阵 ColorMatrix hueColorMatrix = new ColorMatrix(); // 控制让红色区在色轮上旋转的角度 hueColorMatrix.setRotate(0, newHueValue); // 控制让绿红色区在色轮上旋转的角度 hueColorMatrix.setRotate(1, newHueValue); // 控制让蓝色区在色轮上旋转的角度 hueColorMatrix.setRotate(2, newHueValue); // 创建一个画笔并设置其颜色过滤器 Paint paint = new Paint(); paint.setColorFilter(new ColorMatrixColorFilter(hueColorMatrix)); // 创建一个新的图片并创建画布 Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(newBitmap); // 将原图使用给定的画笔画到画布上 canvas.drawBitmap(bitmap, 0, 0, paint); return newBitmap; } /** * 亮度、色相、饱和度处理 * * @param bitmap 原图 * @param lumValue 亮度值 * @param hueValue 色相值 * @param saturationValue 饱和度值 * @return 亮度、色相、饱和度处理后的图片 */ public static Bitmap lumAndHueAndSaturation(Bitmap bitmap, int lumValue, int hueValue, int saturationValue) { // 计算出符合要求的饱和度值 float newSaturationValue = saturationValue * 1.0F / 127; // 计算出符合要求的亮度值 float newlumValue = lumValue * 1.0F / 127; // 计算出符合要求的色相值 float newHueValue = (hueValue - 127) * 1.0F / 127 * 180; // 创建一个颜色矩阵并设置其饱和度 ColorMatrix colorMatrix = new ColorMatrix(); // 设置饱和度值 colorMatrix.setSaturation(newSaturationValue); // 设置亮度值 colorMatrix.setScale(newlumValue, newlumValue, newlumValue, 1); // 控制让红色区在色轮上旋转的角度 colorMatrix.setRotate(0, newHueValue); // 控制让绿红色区在色轮上旋转的角度 colorMatrix.setRotate(1, newHueValue); // 控制让蓝色区在色轮上旋转的角度 colorMatrix.setRotate(2, newHueValue); // 创建一个画笔并设置其颜色过滤器 Paint paint = new Paint(); paint.setColorFilter(new ColorMatrixColorFilter(colorMatrix)); // 创建一个新的图片并创建画布 Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(newBitmap); // 将原图使用给定的画笔画到画布上 canvas.drawBitmap(bitmap, 0, 0, paint); return newBitmap; } /** * 怀旧效果 * * @param bitmap * @return */ public static Bitmap nostalgic(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); Bitmap newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); int pixColor = 0; int pixR = 0; int pixG = 0; int pixB = 0; int newR = 0; int newG = 0; int newB = 0; int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); for (int i = 0; i < height; i++) { for (int k = 0; k < width; k++) { pixColor = pixels[width * i + k]; pixR = Color.red(pixColor); pixG = Color.green(pixColor); pixB = Color.blue(pixColor); newR = (int) (0.393 * pixR + 0.769 * pixG + 0.189 * pixB); newG = (int) (0.349 * pixR + 0.686 * pixG + 0.168 * pixB); newB = (int) (0.272 * pixR + 0.534 * pixG + 0.131 * pixB); int newColor = Color.argb(255, newR > 255 ? 255 : newR, newG > 255 ? 255 : newG, newB > 255 ? 255 : newB); pixels[width * i + k] = newColor; } } newBitmap.setPixels(pixels, 0, width, 0, 0, width, height); return newBitmap; } /** * 柔化效果 * * @param bitmap * @return */ public static Bitmap soften(Bitmap bitmap) { // 高斯矩阵 int[] gauss = new int[]{1, 2, 1, 2, 4, 2, 1, 2, 1}; int width = bitmap.getWidth(); int height = bitmap.getHeight(); Bitmap newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); int pixR = 0; int pixG = 0; int pixB = 0; int pixColor = 0; int newR = 0; int newG = 0; int newB = 0; int delta = 16; // 值越小图片会越亮,越大则越暗 int idx = 0; int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); for (int i = 1, length = height - 1; i < length; i++) { for (int k = 1, len = width - 1; k < len; k++) { idx = 0; for (int m = -1; m <= 1; m++) { for (int n = -1; n <= 1; n++) { pixColor = pixels[(i + m) * width + k + n]; pixR = Color.red(pixColor); pixG = Color.green(pixColor); pixB = Color.blue(pixColor); newR = newR + (int) (pixR * gauss[idx]); newG = newG + (int) (pixG * gauss[idx]); newB = newB + (int) (pixB * gauss[idx]); idx++; } } newR /= delta; newG /= delta; newB /= delta; newR = Math.min(255, Math.max(0, newR)); newG = Math.min(255, Math.max(0, newG)); newB = Math.min(255, Math.max(0, newB)); pixels[i * width + k] = Color.argb(255, newR, newG, newB); newR = 0; newG = 0; newB = 0; } } newBitmap.setPixels(pixels, 0, width, 0, 0, width, height); return newBitmap; } /** * 光照效果 * * @param bitmap * @param centerX 光源在X轴的位置 * @param centerY 光源在Y轴的位置 * @return */ public static Bitmap sunshine(Bitmap bitmap, int centerX, int centerY) { final int width = bitmap.getWidth(); final int height = bitmap.getHeight(); Bitmap newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); int pixR = 0; int pixG = 0; int pixB = 0; int pixColor = 0; int newR = 0; int newG = 0; int newB = 0; int radius = Math.min(centerX, centerY); final float strength = 150F; // 光照强度 100~150 int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); int pos = 0; for (int i = 1, length = height - 1; i < length; i++) { for (int k = 1, len = width - 1; k < len; k++) { pos = i * width + k; pixColor = pixels[pos]; pixR = Color.red(pixColor); pixG = Color.green(pixColor); pixB = Color.blue(pixColor); newR = pixR; newG = pixG; newB = pixB; // 计算当前点到光照中心的距离,平面座标系中求两点之间的距离 int distance = (int) (Math.pow((centerY - i), 2) + Math.pow( centerX - k, 2)); if (distance < radius * radius) { // 按照距离大小计算增加的光照值 int result = (int) (strength * (1.0 - Math.sqrt(distance) / radius)); newR = pixR + result; newG = pixG + result; newB = pixB + result; } newR = Math.min(255, Math.max(0, newR)); newG = Math.min(255, Math.max(0, newG)); newB = Math.min(255, Math.max(0, newB)); pixels[pos] = Color.argb(255, newR, newG, newB); } } newBitmap.setPixels(pixels, 0, width, 0, 0, width, height); return newBitmap; } /** * 底片效果 * * @param bitmap * @return */ public static Bitmap film(Bitmap bitmap) { // RGBA的最大值 final int MAX_VALUE = 255; int width = bitmap.getWidth(); int height = bitmap.getHeight(); Bitmap newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); int pixR = 0; int pixG = 0; int pixB = 0; int pixColor = 0; int newR = 0; int newG = 0; int newB = 0; int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); int pos = 0; for (int i = 1, length = height - 1; i < length; i++) { for (int k = 1, len = width - 1; k < len; k++) { pos = i * width + k; pixColor = pixels[pos]; pixR = Color.red(pixColor); pixG = Color.green(pixColor); pixB = Color.blue(pixColor); newR = MAX_VALUE - pixR; newG = MAX_VALUE - pixG; newB = MAX_VALUE - pixB; newR = Math.min(MAX_VALUE, Math.max(0, newR)); newG = Math.min(MAX_VALUE, Math.max(0, newG)); newB = Math.min(MAX_VALUE, Math.max(0, newB)); pixels[pos] = Color.argb(MAX_VALUE, newR, newG, newB); } } newBitmap.setPixels(pixels, 0, width, 0, 0, width, height); return newBitmap; } /** * 锐化效果 * * @param bitmap * @return */ public static Bitmap sharpen(Bitmap bitmap) { // 拉普拉斯矩阵 int[] laplacian = new int[]{-1, -1, -1, -1, 9, -1, -1, -1, -1}; int width = bitmap.getWidth(); int height = bitmap.getHeight(); Bitmap newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); int pixR = 0; int pixG = 0; int pixB = 0; int pixColor = 0; int newR = 0; int newG = 0; int newB = 0; int idx = 0; float alpha = 0.3F; int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); for (int i = 1, length = height - 1; i < length; i++) { for (int k = 1, len = width - 1; k < len; k++) { idx = 0; for (int m = -1; m <= 1; m++) { for (int n = -1; n <= 1; n++) { pixColor = pixels[(i + n) * width + k + m]; pixR = Color.red(pixColor); pixG = Color.green(pixColor); pixB = Color.blue(pixColor); newR = newR + (int) (pixR * laplacian[idx] * alpha); newG = newG + (int) (pixG * laplacian[idx] * alpha); newB = newB + (int) (pixB * laplacian[idx] * alpha); idx++; } } newR = Math.min(255, Math.max(0, newR)); newG = Math.min(255, Math.max(0, newG)); newB = Math.min(255, Math.max(0, newB)); pixels[i * width + k] = Color.argb(255, newR, newG, newB); newR = 0; newG = 0; newB = 0; } } newBitmap.setPixels(pixels, 0, width, 0, 0, width, height); return newBitmap; } /** * 浮雕效果 * * @param bitmap * @return */ public static Bitmap emboss(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); Bitmap newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); int pixR = 0; int pixG = 0; int pixB = 0; int pixColor = 0; int newR = 0; int newG = 0; int newB = 0; int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); int pos = 0; for (int i = 1, length = height - 1; i < length; i++) { for (int k = 1, len = width - 1; k < len; k++) { pos = i * width + k; pixColor = pixels[pos]; pixR = Color.red(pixColor); pixG = Color.green(pixColor); pixB = Color.blue(pixColor); pixColor = pixels[pos + 1]; newR = Color.red(pixColor) - pixR + 127; newG = Color.green(pixColor) - pixG + 127; newB = Color.blue(pixColor) - pixB + 127; newR = Math.min(255, Math.max(0, newR)); newG = Math.min(255, Math.max(0, newG)); newB = Math.min(255, Math.max(0, newB)); pixels[pos] = Color.argb(255, newR, newG, newB); } } newBitmap.setPixels(pixels, 0, width, 0, 0, width, height); return newBitmap; } }
5.打开相机相关类
package com.example.coshenwancheng.utils; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.provider.MediaStore; import java.io.File; /** * @desc: 打开相机相关类 */ public class CameraUtils { public static final int CAMERA_REQ_CODE = 0x0011; /** * 打开相机 * * @param activity * @param path */ public void openCamera(Activity activity, String path) { openCamera(activity, path, "IMG_" + System.currentTimeMillis() + ".jpg"); } /** * 打开相机 * * @param activity * @param path * @param fileName */ public void openCamera(Activity activity, String path, String fileName) { FileUtils.makeDirs(path); File cameraFile = new File(path, fileName); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)); activity.startActivityForResult(intent, CAMERA_REQ_CODE); } }
6.点击处理方法,防止二次点击
package com.example.coshenwancheng.utils; /** * @description 点击处理方法,防止二次点击 */ public class ClickUtil { // 上次点击时间 private static long sLastTime; /** * 判断此次点击是否响应 * * @return 响应则返回true,否则返回false */ public static boolean isClick() { long time = TimeUtils.getCurTimeMills(); if (sLastTime > time || time - sLastTime > 500) { synchronized (ClickUtil.class) { if (sLastTime > time || time - sLastTime > 500) { sLastTime = time; return true; } return false; } } return false; } }
7.集合操作
package com.example.coshenwancheng.utils; import android.text.TextUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @desc: 集合操作 */ public class CollectionUtils { private static final String DELIMITER = ","; /** * 判断集合是否为空 * * @param c * @param <V> * @return */ public static <V> boolean isEmpty(Collection<V> c) { return (c == null || c.size() == 0); } /** * Join collection to string, separator is {@link #DELIMITER} * * @param tokens * @return */ public static String join(Iterable tokens) { return tokens == null ? "" : TextUtils.join(DELIMITER, tokens); } /** * 将数组转为list * * @param array * @param <T> * @return */ public static <T> List<T> arrayToList(T... array) { return Arrays.asList(array); } /** * 将数组转为set集合 * * @param array * @param <T> * @return */ public static <T> Set<T> arrayToSet(T... array) { return new HashSet<T>(arrayToList(array)); } /** * 集合转为数组 * * @param c * @return */ public static Object[] listToArray(Collection<?> c) { if (!isEmpty(c)) { return c.toArray(); } return null; } /** * list转为set * * @param list * @param <T> * @return */ public static <T> Set<T> listToSet(List<T> list) { return new HashSet<T>(list); } /** * Convert set to list * set转为list * * @param set * @param <T> * @return */ public static <T> List<T> setToList(Set<T> set) { return new ArrayList<T>(set); } /** * Traverse collection * 遍历集合 * * @param c * @param <T> * @return */ public static <T> String traverseCollection(Collection<T> c) { if (!isEmpty(c)) { int len = c.size(); StringBuilder builder = new StringBuilder(len); int i = 0; for (T t : c) { if (t == null) { continue; } builder.append(t.toString()); i++; if (i < len) { builder.append(DELIMITER); } } return builder.toString(); } return null; } }
8.获取CPU信息
package com.example.coshenwancheng.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.util.regex.Pattern; /** * @desc: 获取CPU信息 */ public class CpuUtils { /** * Get cpu max frequence, Unit KHZ. * 获得CPU最大频率,单位千赫。 * * @return */ public static String getCpuMaxFreq() { String result = "N/A"; ProcessBuilder cmd; try { String[] args = {"/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"}; cmd = new ProcessBuilder(args); Process process = cmd.start(); InputStream in = process.getInputStream(); byte[] re = new byte[24]; while (in.read(re) != -1) { result = result + new String(re); } in.close(); } catch (IOException ex) { ex.printStackTrace(); } return result.trim(); } /** * Get cpu min frequence, Unit KHZ. * 获取CPU最小频率,单位千赫 * * @return */ public static String getCpuMinFreq() { String result = "N/A"; ProcessBuilder cmd; try { String[] args = {"/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq"}; cmd = new ProcessBuilder(args); Process process = cmd.start(); InputStream in = process.getInputStream(); byte[] re = new byte[24]; while (in.read(re) != -1) { result = result + new String(re); } in.close(); } catch (IOException ex) { ex.printStackTrace(); } return result.trim(); } /** * Get cpu current frequence, Unit KHZ. * 获取CPU电流频率,单位千赫。 * * @return */ @SuppressWarnings("resource") public static String getCpuCurFreq() { String result = "N/A"; try { FileReader fr = new FileReader("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"); BufferedReader br = new BufferedReader(fr); String text = br.readLine(); result = text.trim(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } /** * Get cpu name * 获得CPU的名字 * * @return */ @SuppressWarnings("resource") public static String getCpuName() { try { FileReader fr = new FileReader("/proc/cpuinfo"); BufferedReader br = new BufferedReader(fr); String text = br.readLine(); String[] array = text.split(":\\s+", 2); for (int i = 0; i < array.length; i++) { } return array[1]; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * Get cpu cores * 获取CPU核心数 * * @return */ public static int getCpuCores() { class CpuFilter implements FileFilter { @Override public boolean accept(File pathname) { if (Pattern.matches("cpu[0-9]", pathname.getName())) { return true; } return false; } } try { File dir = new File("/sys/devices/system/cpu/"); File[] files = dir.listFiles(new CpuFilter()); return files.length; } catch (Exception e) { e.printStackTrace(); return 1; } } }
9.时间转换工具类
package com.example.coshenwancheng.utils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * @description 时间转换工具类 */ public class DateToStringUtils { /** * 字符串转换到时间格式 * @param dateStr 需要转换的字符串 * @return dateFormatStr 需要转换的字符串的时间格式 * @param formatStr 需要格式的目标字符串 举例 yyyyMMdd * @return String 返回转换后的时间字符串 * @throws ParseException 转换异常 */ public static String StringToDate(String dateStr,String dateFormatStr,String formatStr){ DateFormat sdf=new SimpleDateFormat(dateFormatStr); Date date=null; try { date = sdf.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } SimpleDateFormat s=new SimpleDateFormat(formatStr); return s.format(date); } public static String StringToDate2(long dateStr,String dateFormatStr,String formatStr){ DateFormat sdf=new SimpleDateFormat(dateFormatStr); Date date=null; try { date = sdf.parse(String.valueOf(dateStr)); } catch (ParseException e) { e.printStackTrace(); } SimpleDateFormat s=new SimpleDateFormat(formatStr); return s.format(date); } }
10.常用单位转换的辅助类
package com.example.coshenwancheng.utils; import android.content.Context; import android.util.TypedValue; /** * 常用单位转换的辅助类 */ public class DensityUtils { private DensityUtils() { /** cannot be instantiated **/ throw new UnsupportedOperationException("cannot be instantiated"); } /** * dp转px * * @param context * @param dpVal * @return */ public static int dp2px(Context context, float dpVal) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, context.getResources().getDisplayMetrics()); } /** * sp转px * * @param context * @param spVal * @return */ public static int sp2px(Context context, float spVal) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, context.getResources().getDisplayMetrics()); } /** * px转dp * * @param context * @param pxVal * @return */ public static float px2dp(Context context, float pxVal) { final float scale = context.getResources().getDisplayMetrics().density; return (pxVal / scale); } /** * px转sp * * @param context * @param pxVal * @return */ public static float px2sp(Context context, float pxVal) { return (pxVal / context.getResources().getDisplayMetrics().scaledDensity); } }