zoukankan      html  css  js  c++  java
  • android文件和图片的处理工具类(一)

      1 package com.gzcivil.utils;
      2 
      3 import java.io.File;
      4 import java.io.FileInputStream;
      5 import java.io.FileOutputStream;
      6 import java.io.InputStream;
      7 import java.math.BigDecimal;
      8 import java.text.DecimalFormat;
      9 import java.util.List;
     10 import java.util.UUID;
     11 
     12 import android.app.ActivityManager;
     13 import android.content.ActivityNotFoundException;
     14 import android.content.Context;
     15 import android.content.Intent;
     16 import android.content.pm.PackageInfo;
     17 import android.content.pm.PackageManager.NameNotFoundException;
     18 import android.graphics.Bitmap;
     19 import android.graphics.BitmapFactory;
     20 import android.graphics.drawable.BitmapDrawable;
     21 import android.graphics.drawable.Drawable;
     22 import android.media.ThumbnailUtils;
     23 import android.net.Uri;
     24 import android.os.Environment;
     25 import android.telephony.TelephonyManager;
     26 import android.view.View;
     27 import android.view.ViewGroup;
     28 import android.widget.ImageView;
     29 import android.widget.ListAdapter;
     30 import android.widget.ListView;
     31 
     32 import com.gzcivil.R;
     33 import com.igexin.sdk.PushManager;
     34 
     35 public class CommonUtil {
     36 
     37     /**
     38      * 回收ImageView图片
     39      * 
     40      * @param imageView
     41      */
     42     public static synchronized void recycleImage(ImageView imageView) {
     43         if (imageView == null)
     44             return;
     45         Drawable drawable = imageView.getDrawable();
     46         recycleDrawable(drawable);
     47         imageView.setImageBitmap(null);
     48     }
     49 
     50     /**
     51      * 回收View背景图片
     52      * 
     53      * @param view
     54      */
     55     @SuppressWarnings("deprecation")
     56     public static synchronized void recycleBackground(View view) {
     57         if (view == null)
     58             return;
     59         Drawable drawable = view.getBackground();
     60         recycleDrawable(drawable);
     61         view.setBackgroundDrawable(null);
     62     }
     63 
     64     /**
     65      * 回收方法
     66      */
     67     private static void recycleDrawable(Drawable drawable) {
     68         if (drawable != null && drawable instanceof BitmapDrawable) {
     69             Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
     70             if (bitmap != null && !bitmap.isRecycled()) {
     71                 LogUtils.e(SysUtils.LOG_TAG, "图片回收了");
     72                 bitmap.recycle();
     73             }
     74         }
     75     }
     76 
     77     public static double getDirSize(File file) {
     78         // 判断文件是否存在
     79         if (file.exists()) {
     80             // 如果是目录则递归计算其内容的总大小
     81             if (file.isDirectory()) {
     82                 File[] children = file.listFiles();
     83                 double size = 0;
     84                 for (File f : children)
     85                     size += getDirSize(f);
     86                 return size;
     87             } else {// 如果是文件则直接返回其大小,以“兆”为单位
     88                 return file.length();
     89             }
     90         } else {
     91             return 0.0;
     92         }
     93     }
     94 
     95     public static String FormetFileSize(double fileS) {// 转换文件大小
     96         DecimalFormat df = new DecimalFormat("#.00");
     97         String fileSizeString = "";
     98         if (fileS < 1024) {
     99             fileSizeString = "0.0" + "B";
    100         } else if (fileS < 1048576) {
    101             fileSizeString = df.format((double) fileS / 1024) + "K";
    102         } else if (fileS < 1073741824) {
    103             fileSizeString = df.format((double) fileS / 1048576) + "M";
    104         } else {
    105             fileSizeString = df.format((double) fileS / 1073741824) + "G";
    106         }
    107         return fileSizeString;
    108     }
    109 
    110     /*
    111      * Java文件操作 获取文件扩展名
    112      */
    113     public static String getExtensionName(String filename) {
    114         if ((filename != null) && (filename.length() > 0)) {
    115             int dot = filename.lastIndexOf('.');
    116             if ((dot > -1) && (dot < (filename.length() - 1))) {
    117                 return filename.substring(dot + 1);
    118             }
    119         }
    120         return filename;
    121     }
    122 
    123     /*
    124      * Java文件操作 获取不带扩展名的文件名
    125      */
    126     public static String getFileNameNoEx(String filename) {
    127         if ((filename != null) && (filename.length() > 0)) {
    128             int dot = filename.lastIndexOf('.');
    129             if ((dot > -1) && (dot < (filename.length()))) {
    130                 return filename.substring(0, dot);
    131             }
    132         }
    133         return filename;
    134     }
    135 
    136     public static void setListViewHeightBasedOnChildren(ListView listView) {
    137         ListAdapter listAdapter = listView.getAdapter();
    138         if (listAdapter == null) {
    139             return;
    140         }
    141 
    142         int totalHeight = 0;
    143         for (int i = 0; i < listAdapter.getCount(); i++) {
    144             View listItem = listAdapter.getView(i, null, listView);
    145             listItem.measure(0, 0);
    146             totalHeight += listItem.getMeasuredHeight();
    147         }
    148 
    149         ViewGroup.LayoutParams params = listView.getLayoutParams();
    150         params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    151         listView.setLayoutParams(params);
    152     }
    153 
    154     /**
    155      * 检查是否存在SDCard
    156      * 
    157      * @return
    158      */
    159     public static boolean hasSdcard() {
    160         String state = Environment.getExternalStorageState();
    161         if (state.equals(Environment.MEDIA_MOUNTED)) {
    162             return true;
    163         } else {
    164             return false;
    165         }
    166     }
    167 
    168     /**
    169      * 四舍五入
    170      * 
    171      * @param v
    172      * @param scale
    173      *            多少位
    174      * @return
    175      */
    176     public static double decimalFormat(Float v, int scale) {
    177         if (scale < 0) {
    178             throw new IllegalArgumentException("The scale must be a positive integer or zero");
    179         }
    180         BigDecimal b = new BigDecimal(Double.toString(v));
    181         BigDecimal one = new BigDecimal("1");
    182         return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).floatValue();
    183     }
    184 
    185     // 获取个推CID
    186     public static String GetCid(Context context) {
    187         return PushManager.getInstance().getClientid(context);
    188     }
    189 
    190     // 获取机器码
    191     public static String GetMachineCode(Context context) {
    192         String code = "";
    193         final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    194         final String tmDevice, tmSerial, androidId;
    195         tmDevice = "" + tm.getDeviceId();
    196         tmSerial = "" + tm.getSimSerialNumber();
    197         androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
    198         UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
    199         code = deviceUuid.toString();
    200         return code;
    201     }
    202 
    203     /**
    204      * 派单状态
    205      * 
    206      * @param param
    207      * @return
    208      */
    209     public static String getCheetStatus(String param) {
    210         if (param == null || param.equals("")) {
    211             return "";
    212         }
    213         String Status = "";
    214         if (param == "00" || param.equals("00")) {
    215             Status = "<font color='#e53c41'>未接</font>";
    216         } else if (param == "01" || param.equals("01")) {
    217             Status = "<font color='#e53c41'>执行中</font>";
    218         } else if (param == "02" || param.equals("02")) {
    219             Status = "<font color='#2ab823'>完成</font>";
    220         } else if (param == "08" || param.equals("08")) {
    221             Status = "<font color='#f13f1b'>终止</font>";
    222         } else if (param == "09" || param.equals("09")) {
    223             Status = "<font color='#f13f1b'>拒收</font>";
    224         } else {
    225             Status = "";
    226         }
    227         return Status;
    228     }
    229 
    230     /**
    231      * 会议通知状态
    232      * 
    233      * @param param
    234      * @return
    235      */
    236     public static String getMeetStatus(String param) {
    237         String Status = "";
    238         if (param == null || param.equals("")) {
    239             return Status;
    240         }
    241         if (param.equals("1")) {
    242             Status = "<font color='#e53c41'>未接</font>";
    243         } else if (param.equals("2")) {
    244             Status = "<font color='#2ab823'>已同意</font>";
    245         } else if (param.equals("3")) {
    246             Status = "<font color='#f13f1b'>请假</font>";
    247         }
    248         return Status;
    249     }
    250 
    251     /**
    252      * 检测应用程序 是否前台运行
    253      * 
    254      * @param context
    255      * @return
    256      */
    257     public static boolean isServiceStarted(Context context) {
    258         boolean isStarted = false;
    259         try {
    260             ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    261             int intGetTastCounter = 1000;
    262             List<ActivityManager.RunningServiceInfo> mRunningService = mActivityManager.getRunningServices(intGetTastCounter);
    263             for (ActivityManager.RunningServiceInfo amService : mRunningService) {
    264                 if (0 == amService.service.getPackageName().compareTo("com.msd.terminal")) {
    265                     isStarted = true;
    266                     break;
    267                 }
    268             }
    269         } catch (SecurityException e) {
    270             e.printStackTrace();
    271         }
    272         return isStarted;
    273     }
    274 
    275     public static boolean isServiceRunning(Context mContext, String className) {
    276         boolean isRunning = false;
    277         ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
    278         List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(30);
    279         if (!(serviceList.size() > 0)) {
    280             return false;
    281         }
    282         for (int i = 0; i < serviceList.size(); i++) {
    283             if (serviceList.get(i).service.getClassName().equals(className) == true) {
    284                 isRunning = true;
    285                 break;
    286             }
    287         }
    288         return isRunning;
    289     }
    290 
    291     // 获取版本号
    292     public static String getVersion(Context context) {
    293         try {
    294             PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
    295             return pi.versionName;
    296         } catch (NameNotFoundException e) {
    297             e.printStackTrace();
    298             return context.getString(R.string.version_unknown);
    299         }
    300     }
    301 
    302     /** 保存方法 */
    303     public static boolean saveBigImgToSmall(String bigImgPath, String smallImgPath, String smallImgName, int min) {
    304 
    305         boolean flag = false;
    306         try {
    307             File lFile = new File(bigImgPath);
    308             if (lFile.exists() && lFile.isFile()) {
    309                 InputStream is = new FileInputStream(bigImgPath);
    310                 Bitmap bitmap = BitmapFactory.decodeStream(is, null, getBitmapOption());
    311                 int w = bitmap.getWidth();
    312                 int h = bitmap.getHeight();
    313                 LogUtils.e(SysUtils.LOG_TAG, "压缩前:w = " + w + ", h = " + h);
    314                 if (min < 200) {
    315                     min = 200;
    316                 }
    317                 if (w > h) {
    318                     w = w * min / h;
    319                     h = min;
    320                 } else {
    321                     h = h * min / w;
    322                     w = min;
    323                 }
    324                 LogUtils.e(SysUtils.LOG_TAG, "压缩后:w = " + w + ", h = " + h);
    325                 // 压缩原图为小图显示
    326                 bitmap = ThumbnailUtils.extractThumbnail(bitmap, w, h, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
    327                 File f = new File(smallImgPath);
    328                 if (f.exists())
    329                     f.delete();
    330                 FileOutputStream out = new FileOutputStream(f);
    331                 flag = bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
    332                 out.flush();
    333                 out.close();
    334             }
    335         } catch (Exception e) {
    336             e.printStackTrace();
    337         }
    338         return flag;
    339     }
    340 
    341     /**
    342      * 获取Bitmap的读取参数
    343      */
    344     public static final BitmapFactory.Options getBitmapOption() {
    345         BitmapFactory.Options opt = new BitmapFactory.Options();
    346         opt.inPreferredConfig = Bitmap.Config.RGB_565;
    347         opt.inPurgeable = true;
    348         opt.inInputShareable = true;
    349         return opt;
    350     }
    351 
    352     public static void openFile(Context context, File file) {
    353         try {
    354             Intent intent = new Intent();
    355             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    356             // 设置intent的Action属性
    357             intent.setAction(Intent.ACTION_VIEW);
    358             // 获取文件file的MIME类型
    359             String type = getMIMEType(file);
    360             // 设置intent的data和Type属性。
    361             intent.setDataAndType(Uri.fromFile(file), type);
    362             // 跳转
    363             context.startActivity(intent);
    364             // Intent.createChooser(intent, "请选择对应的软件打开该附件!");
    365         } catch (ActivityNotFoundException e) {
    366             // TODO: handle exception
    367             MyToast.showToast(context, "sorry附件不能打开,请下载相关软件!", 0);
    368         }
    369     }
    370 
    371     private static String getMIMEType(File file) {
    372 
    373         String type = "*/*";
    374         String fName = file.getName();
    375         // 获取后缀名前的分隔符"."在fName中的位置。
    376         int dotIndex = fName.lastIndexOf(".");
    377         if (dotIndex < 0) {
    378             return type;
    379         }
    380         /* 获取文件的后缀名 */
    381         String end = fName.substring(dotIndex, fName.length()).toLowerCase();
    382         if (end == "")
    383             return type;
    384         // 在MIME和文件类型的匹配表中找到对应的MIME类型。
    385         for (int i = 0; i < MIME_MapTable.length; i++) {
    386 
    387             if (end.equals(MIME_MapTable[i][0]))
    388                 type = MIME_MapTable[i][1];
    389         }
    390         return type;
    391     }
    392 
    393     // 可以自己随意添加
    394     private static String[][] MIME_MapTable = {
    395             // {后缀名,MIME类型}
    396             { ".3gp", "video/3gpp" }, { ".apk", "application/vnd.android.package-archive" }, { ".asf", "video/x-ms-asf" }, { ".avi", "video/x-msvideo" }, { ".bin", "application/octet-stream" }, { ".bmp", "image/bmp" }, { ".c", "text/plain" }, { ".class", "application/octet-stream" }, { ".conf", "text/plain" }, { ".cpp", "text/plain" }, { ".doc", "application/msword" }, { ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }, { ".xls", "application/vnd.ms-excel" }, { ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }, { ".exe", "application/octet-stream" }, { ".gif", "image/gif" }, { ".gtar", "application/x-gtar" }, { ".gz", "application/x-gzip" }, { ".h", "text/plain" }, { ".htm", "text/html" }, { ".html", "text/html" },
    397             { ".jar", "application/java-archive" }, { ".java", "text/plain" }, { ".jpeg", "image/jpeg" }, { ".jpg", "image/jpeg" }, { ".js", "application/x-javascript" }, { ".log", "text/plain" }, { ".m3u", "audio/x-mpegurl" }, { ".m4a", "audio/mp4a-latm" }, { ".m4b", "audio/mp4a-latm" }, { ".m4p", "audio/mp4a-latm" }, { ".m4u", "video/vnd.mpegurl" }, { ".m4v", "video/x-m4v" }, { ".mov", "video/quicktime" }, { ".mp2", "audio/x-mpeg" }, { ".mp3", "audio/x-mpeg" }, { ".mp4", "video/mp4" }, { ".mpc", "application/vnd.mpohun.certificate" }, { ".mpe", "video/mpeg" }, { ".mpeg", "video/mpeg" }, { ".mpg", "video/mpeg" }, { ".mpg4", "video/mp4" }, { ".mpga", "audio/mpeg" }, { ".msg", "application/vnd.ms-outlook" }, { ".ogg", "audio/ogg" }, { ".pdf", "application/pdf" }, { ".png", "image/png" },
    398             { ".pps", "application/vnd.ms-powerpoint" }, { ".ppt", "application/vnd.ms-powerpoint" }, { ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" }, { ".prop", "text/plain" }, { ".rc", "text/plain" }, { ".rmvb", "audio/x-pn-realaudio" }, { ".rtf", "application/rtf" }, { ".sh", "text/plain" }, { ".tar", "application/x-tar" }, { ".tgz", "application/x-compressed" }, { ".txt", "text/plain" }, { ".wav", "audio/x-wav" }, { ".wma", "audio/x-ms-wma" }, { ".wmv", "audio/x-ms-wmv" }, { ".wps", "application/vnd.ms-works" }, { ".xml", "text/plain" }, { ".z", "application/x-compress" }, { ".zip", "application/x-zip-compressed" }, { "", "*/*" } };
    399 
    400 }
  • 相关阅读:
    DML数据操作语言练习
    表的操作练习
    20151218--地区导航习题
    20151217--Ajax的一点补充
    02151216--Ajax
    json(转)
    Node.js(转) -- 临时来说还看不懂!
    20151113--JSTL
    20151210--MVC
    链表(转)
  • 原文地址:https://www.cnblogs.com/lijinlun0825/p/5174667.html
Copyright © 2011-2022 走看看