您的位置:首页 > 移动开发 > Android开发

android开发常用工具方法

2016-05-23 15:10 549 查看
在软件开发过程中常会用到一些工具方法,现对上一个项目所用的方法做一总结:

package com.elabing.android.client.utils;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.text.DecimalFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Calendar;

import java.util.List;

import java.util.Locale;

import java.util.Random;

import java.util.TimeZone;

import java.util.UUID;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import java.util.regex.PatternSyntaxException;

import org.apache.commons.io.FileUtils;

import org.apache.commons.lang.StringUtils;

import android.content.Context;

import android.content.Intent;

import android.content.pm.ApplicationInfo;

import android.content.pm.PackageManager;

import android.content.pm.PackageManager.NameNotFoundException;

import android.content.res.Resources;

import android.database.Cursor;

import android.graphics.Bitmap;

import android.graphics.Bitmap.CompressFormat;

import android.graphics.Bitmap.Config;

import android.graphics.BitmapFactory;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.PixelFormat;

import android.graphics.drawable.BitmapDrawable;

import android.graphics.drawable.Drawable;

import android.media.ThumbnailUtils;

import android.net.ConnectivityManager;

import android.net.NetworkInfo;

import android.net.Uri;

import android.os.AsyncTask;

import android.os.Bundle;

import android.provider.MediaStore;

import android.provider.Settings.Secure;

import android.text.Editable;

import android.text.TextWatcher;

import android.view.View;

import android.view.ViewGroup;

import android.view.WindowManager;

import android.widget.AbsListView;

import android.widget.AbsListView.OnScrollListener;

import android.widget.EditText;

import android.widget.ImageView;

import android.widget.ListAdapter;

import android.widget.ListView;

import android.widget.TextView;

import android.widget.Toast;

import com.elabing.android.client.R;

import com.elabing.android.client.RenRenApplication;

import com.elabing.android.client.activity.BaseActivity;

import com.elabing.android.client.bean.GoodTypeInfo;

import com.elabing.android.client.bean.GoodTypeInfoFistLevResponse;

import com.elabing.android.client.bean.MobileInfo;

import com.elabing.android.client.bean.UnReadMessageCountResponse;

import com.elabing.android.client.lib.swipview.SwipeMenu;

import com.elabing.android.client.lib.swipview.SwipeMenuCreator;

import com.elabing.android.client.lib.swipview.SwipeMenuItem;

import com.elabing.android.client.net.Api;

import com.nostra13.universalimageloader.core.DisplayImageOptions;

import com.nostra13.universalimageloader.core.ImageLoader;

public class CommonUtil {

public static boolean hasOrderPackageAction = false;

/**
*
* @param context
* @return
*/
public static String getChannelValue(Context context) {
String result = "";
ApplicationInfo appInfo;
try {
appInfo = context.getPackageManager().getApplicationInfo(
context.getPackageName(), PackageManager.GET_META_DATA);
// result = appInfo.metaData.getString("UMENG_CHANNEL");
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return result;
}

public static MobileInfo getMobileInfo() {
MobileInfo result = new MobileInfo();
try {
String mobileName = android.os.Build.BRAND;
String mobileModel = android.os.Build.MODEL;
String mobileSdkVersion = "" + android.os.Build.VERSION.SDK_INT;
result.setBrean(mobileName);
result.setModel(mobileModel);
result.setSdkVersion(mobileSdkVersion);
} catch (Exception e) {
e.printStackTrace();
result = null;
}
return result;

}

/**
* 获取渠道号码
*
* @param context
* @return
*/
public static String getChannelValue2(Context context) {
String result = "";
ApplicationInfo appInfo;
try {
appInfo = context.getPackageManager().getApplicationInfo(
context.getPackageName(), PackageManager.GET_META_DATA);
result = appInfo.metaData.getString("UMENG_CHANNEL");
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return result;
}

/**
* 获取应用版本号(供应用市场使用的,用户不可见。通过数字大小来判断是否需要更新)
*
* @param context
* @return 应用版本号
*/
public static int getVersionCode(Context context) {
int code = 0;
try {
code = context.getPackageManager().getPackageInfo(
context.getPa
f0d9
ckageName(), 0).versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return code;
}

public static String getPkgName(Context context) {
String pkg = "";
try {
pkg = context.getPackageName();
} catch (Exception e) {
e.printStackTrace();
}
return pkg;
}

/**
* 获取应用版本名称(用户可见)
*
* @param context
* @return 应用版本名称
*/
public static String getVersionName(Context context) {
String code = "";
try {
code = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return code;
}

/**
* 获取设备号
*
* @param context
* @return 设备号
*/
public static String getDeviceNum(Context context) {
return Secure
.getString(context.getContentResolver(), Secure.ANDROID_ID);

}

/**
* 获取一个UUID值
*
* @return
*/
public static String getUUID() {
return UUID.randomUUID().toString();
}

/**
* 将一个图片对象转化为一个数组
*
* @param drawable
* @return
*/
public static byte[] drawableToByteArray(Drawable drawable) {
int width = drawable.getIntrinsicWidth();

int height = drawable.getIntrinsicHeight();

Bitmap bitmap = Bitmap.createBitmap(width, height,

drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888

: Bitmap.Config.RGB_565);

Canvas canvas = new Canvas(bitmap);

drawable.setBounds(0, 0, width, height);

drawable.draw(canvas);
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return out.toByteArray();
}

/**
* 将一个数组转化为一个图片对象
*
* @param res
* @param bytearray
* @return
*/
public static Drawable byteArrayToDrawable(Resources res, byte[] bytearray) {
if (bytearray != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(bytearray, 0,
bytearray.length);
return new BitmapDrawable(res, bitmap);
} else {
return null;
}
}

/**
* 复制一个文件
*
* @param srcFile
* @param destFile
*/
public static void copyFile(File srcFile, File destFile) {
try {
FileUtils.copyFile(srcFile, destFile);
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 复制一个文件到一个文件目录
*
* @param srcFile
* @param destDir
*/
public static void copyFileToDirectory(File srcFile, File destDir) {
if (!destDir.exists()) {
destDir.mkdirs();
}
try {
FileUtils.copyFileToDirectory(srcFile, destDir);
} catch (IOException e) {
e.printStackTrace();
}
}

public static boolean convertBitmapToFile(Bitmap bitmap, File file) {
boolean result = false;
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
result = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
result = false;
} catch (IOException e) {
e.printStackTrace();
result = false;
}
return result;
}

/**
* 判断网络状态
*/
public static boolean isEnabledNetWork(Context context) {
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
return (info != null && info.isConnected());
}

public static Calendar getCalendar(long millis) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
cal.setTimeZone(TimeZone.getDefault());
return cal;
}

/**
* 获取文件大小,字节数
*
* @param file
* @return
*/
public static long getFileSize(File file) {
if (file != null) {
return file.length();
} else {
return 0;
}
}

public static long getFileSize(String filePath) {
File file = new File(filePath);
return getFileSize(file);
}

/**
* 将字节转为M,保留两位小数
*
* @param b
* @return
*/
public static double convertByteToMb(long b) {
System.out.println(b);
return b / (1000000);
}

/**
* 获取文件的大小,m
*
* @param filePath
* @return
*/
public static double getFileSizeToMb(String filePath) {

return convertByteToMb(getFileSize(filePath));
}

/**
* 压缩bitmap
*
* @param path
* @return
*/
public static Bitmap compressBmp(String path) throws Exception {
BitmapFactory.Options newOpts = new BitmapFactory.Options();

newOpts.inJustDecodeBounds = true;// 只读边,不读内容
newOpts.inJustDecodeBounds = false;
Bitmap bitmap = null;
for (int i = 0; i < 3; i++) {
try {
bitmap = BitmapFactory.decodeFile(path, newOpts);
break;
} catch (OutOfMemoryError e) {
// TODO: handle exception
}
}
if (null == bitmap) {
throw new Exception();
}
int w = newOpts.outWidth;
int h = newOpts.outHeight;
float hh = 800f;//
float ww = 480f;//
int be = 1;
if (w > h && w > ww) {
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;// 设置采样率

newOpts.inPreferredConfig = Config.ARGB_8888;// 该模式是默认的,可不设
newOpts.inPurgeable = true;// 同时设置才会有效
newOpts.inInputShareable = true;// 。当系统内存不够时候图片自动被回收

bitmap = BitmapFactory.decodeFile(path, newOpts);
return bitmap;
}

/**
* 获取一个随机码
*
* @return
*/
public static int generateValidateCode() {
Random random = new Random();
int nextInt = 0;
do {
nextInt = random.nextInt(999999);
} while (nextInt < 100000);
return nextInt;
}

/**
* 下载一个图片为直角的图片
*
* @param url
* @param imageView
*/
public static void downloadIcon2View(String url, ImageView imageView,
int emptyResId, int onFailResId) {
ImageLoader.getInstance().displayImage(
url,
imageView,
RenRenApplication.getImageLoaderOptions(false, emptyResId,
onFailResId));
}

/**
* 下载一个图片为圆角形
*
* @param url
* @param imageView
*/
public static void downloadIcon2ViewRound(String url, ImageView imageView,
int emptyResId, int onFailResId) {
ImageLoader.getInstance().displayImage(
url,
imageView,
RenRenApplication.getImageLoaderOptions(true, emptyResId,
onFailResId));
}

/**
* 下载一个图片格式为纯圆形的
*
* @param url
* @param imageView
*/
public static void downloadIcon2ViewCircle(String url, ImageView imageView) {
ImageLoader.getInstance().displayImage(url, imageView,
RenRenApplication.getImageLoaderOptionsOfCircle());
}

public static boolean isPhoneNumber(String phoneNumber) {
if (StringUtils.isEmpty(phoneNumber))
return false;
if (phoneNumber.length() == 11) {
String pattern = "(^(13\\d|14[57]|15[^4,\\D]|17[678]|18\\d)\\d{8}|170[059]\\d{7})$";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(phoneNumber);
return m.find();// 是手机号
} else
return false;
}

public static String parseListData2Str(List<String> bodyList) {
String result = "";
if (bodyList != null) {
for (String body : bodyList) {
result = result + body;
}
}
return result;
}

/**
* 拨打电话
*
* @param mContext
* @param phoneNum
*/
public static void callPhone(Context mContext, String phoneNum) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
+ phoneNum));
mContext.startActivity(intent);
}

/**
* 获得屏幕宽高
*/
public static int getWidht(Context context) {
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
return manager.getDefaultDisplay().getWidth();
}

public static int getHeight(Context context) {
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
return manager.getDefaultDisplay().getHeight();
}

/**
* 设置swipeview删除布局
*
* @param context
* @param color
* @param resId
* @return
*/
public static SwipeMenuCreator getSwipeView(final Context context,
final Drawable drawable, final int resId, final int width,
final String text) {
// step 1. create a MenuCreator
SwipeMenuCreator creator = new SwipeMenuCreator() {

@Override
public void create(SwipeMenu menu) {
SwipeMenuItem deleteItem = new SwipeMenuItem(context);
deleteItem.setBackground(drawable);
deleteItem.setWidth(width);
if (!text.equals("")) {
deleteItem.setTitle(text);
deleteItem.setTitleSize(14);
deleteItem.setTitleColor(Color.WHITE);
}
if (resId != 0) {
deleteItem.setIcon(resId);
}
menu.addMenuItem(deleteItem);
}
};
return creator;

}

/***
* 动态设置listview的高度
*
* @param listView
*/
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
// params.height += 5;// if without this statement,the listview will be
// a
// little short
// listView.getDividerHeight()获取子项间分隔符占用的高度
// params.height最后得到整个ListView完整显示需要的高度
listView.setLayoutParams(params);
}

/**
* @param listView
* @param requestDataTask
* @param pageSize
*            每次请求的多少条
*/
public static void registerDividePageListener(ListView listView,
final RequestDividePageTask requestDataTask, final List dataSource,
final int pageSize) {
listView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
if ((view.getCount()) == view.getLastVisiblePosition() + 1) {
int pageIndex = view.getCount();
requestDataTask.updateData(dataSource.size(), pageSize);
}
}
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
});
}

public static void showNoMoreDataTip(BaseActivity activity) {
Toast.makeText(activity, "无更多数据...", 1).show();

}

/**
* 从相册选择图片返回图片地址
*
* @param mContext
* @param data
* @return
*/
public static String chooseImageFromPhotoAlbum(Context mContext, Intent data) {
String picturePath = null;
Uri selectedImage = data.getData();
if (selectedImage != null) {
String[] filePathColumns = { MediaStore.Images.Media.DATA };
Cursor c = mContext.getContentResolver().query(selectedImage,
filePathColumns, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePathColumns[0]);
picturePath = c.getString(columnIndex);
c.close();
} else {
FileOutputStream stream = null;
try {
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
if (bitmap != null) {

picturePath = Constants.FOLDER_IMAGE
+ System.currentTimeMillis() + ".jpg";
stream = new FileOutputStream(picturePath);
bitmap.compress(CompressFormat.PNG, 100, stream);
stream.flush();
stream.close();
bitmap.recycle();
bitmap = null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return picturePath;
}

/**
* 获取显示的支付方式
*
* @param paytype
* @return
*/
public static String getPayType(String paytype) {
if (paytype.equals("1")) {
return "支付宝";
} else if (paytype.equals("2")) {
return "微信";
} else {
return "银联";
}
}

/**
* 获取一个月前的日期
*
* @param dateStr
* @return
*/
public static String getBeforeMonthDate(String dateStr) {
SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = null;
try {
date = sim.parse(dateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);

String reStr = sim.format(cal.getTime());
return reStr;

}

/**
* 获取一月前的Calendar
*
* @param dateStr
* @return
*/
public static Calendar getBeforeMonthCalendar(String dateStr) {
SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = null;
try {
date = sim.parse(dateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
return cal;

}

public static DisplayImageOptions initOptions(int imageId) {
DisplayImageOptions options = null;
options = new DisplayImageOptions.Builder().showImageOnLoading(imageId)
.showImageForEmptyUri(imageId).showImageOnFail(imageId)
.cacheInMemory(true).cacheOnDisk(true).considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565).build();
return options;

}

/**
* 将彩色图转换为纯黑白二色
*
* @param 位图
* @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;
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, Config.RGB_565);
// 设置图片数据
newBmp.setPixels(pixels, 0, width, 0, 0, width, height);

Bitmap resizeBmp = ThumbnailUtils.extractThumbnail(newBmp, 380, 460);
return resizeBmp;
}

/**
* 获取未读消息个数并设置ui
*
* @param context
* @param tv
* @param isShowNumber
*/
public static void updateUnReadCountMessage(final Context context,
final TextView tv, final boolean isShowNumber) {
new AsyncTask<Void, Void, UnReadMessageCountResponse>() {

@Override
protected UnReadMessageCountResponse doInBackground(Void... arg0) {
UnReadMessageCountResponse unReadMessageCount = null;
try {
unReadMessageCount = Api.getInstance(context)
.getUnReadMessageCount(2);
return unReadMessageCount;
} catch (Exception e) {
e.printStackTrace();
}
return unReadMessageCount;
}

protected void onPostExecute(UnReadMessageCountResponse result) {
if (result == null || result.getCode() == -1) {
tv.setVisibility(View.INVISIBLE);
} else {
if (result.getTotal() <= 0) {
tv.setVisibility(View.INVISIBLE);
} else {
if (isShowNumber) {
tv.setText("" + result.getTotal());
tv.setVisibility(View.VISIBLE);
} else {
tv.setVisibility(View.INVISIBLE);
}
}
}
};
}.execute();
}

/**
* 点击消息
*
* @param context
* @param messageId
*/
public static void setMessageIsRead(final Context context,
final String messageId) {
new AsyncTask<Void, Void, Void>() {

@Override
protected Void doInBackground(Void... arg0) {
try {
Api.getInstance(context).readMessage(messageId);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute();
}

/**
* 邮箱的验证
*
* @param str
* @return true 为验证正确,false 为失败
*/
public static boolean isEmail(String str) {
Pattern pattern = Pattern
.compile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$");
Matcher mat = pattern.matcher(str);
return mat.matches();
}

/**
* 文件是否存在
*
* @param path
* @return
*/
public static boolean fileIsExists(String path) {
try {
File f = new File(path);
if (!f.exists()) {
return false;
}

} catch (Exception e) {
// TODO: handle exception
return false;
}
return true;
}

/**
* 调用可能打开文件的软件打开文件
*
* @param file
*/
public static void openFile(File file, Context context) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 设置intent的Action属性
intent.setAction(Intent.ACTION_VIEW);
// 获取文件file的MIME类型
String type = getMIMEType(file);
// 设置intent的data和Type属性。
intent.setDataAndType(/* uri */Uri.fromFile(file), type);
// 跳转
try {
context.startActivity(intent); // 可能无应用可打开, 避免程序崩溃
} catch (Exception e) {
Toast.makeText(context, "无应用可打开此文件", Toast.LENGTH_SHORT).show();
return;
}
}

/**
* 根据文件后缀名获得对应的MIME类型。
*
* @param file
*/
private static String getMIMEType(File file) {

String type = "*/*";
String fName = file.getName();
// 获取后缀名前的分隔符"."在fName中的位置。
int dotIndex = fName.lastIndexOf(".");
if (dotIndex < 0) {
return type;
}
/* 获取文件的后缀名 */
String end = fName.substring(dotIndex, fName.length()).toLowerCase(
Locale.CHINA);
if (end == "")
return type;
// 在MIME和文件类型的匹配表中找到对应的MIME类型。
for (int i = 0; i < FileFormatParams.MIME_MapTable.length; i++) {
if (end.equals(FileFormatParams.MIME_MapTable[i][0]))
type = FileFormatParams.MIME_MapTable[i][1];
}
return type;
}
/**
* 邮编验证
* @param post
* @return
*/
public static boolean checkPost(String post){
if(post.matches("[0-9]\\d{5}(?!\\d)")){
return true;
}else{
return false;
}
}

/**
*
* @param str 需要过滤的字符串
* @param regEx //要过滤掉的字符     String regEx = "[/\:*?<>|\"\n\t]";
* @return
* @throws PatternSyntaxException
*/
public static String StringFilter(String str,String regEx)throws PatternSyntaxException{
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}

/**
* 过滤字符
* @param et
*/
public static void setEditTextFilter(final EditText et,String regEx ){
et.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
String editable = et.getText().toString();
String str = CommonUtil.StringFilter(editable, " ");
if(!editable.equals(str)){
et.setText(str);
et.setSelection(str.length()); //光标置后
}
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub

}
});

}

/**
* 黑白处理
* @param img
* @return
*/
public static Bitmap binarization(Bitmap img) {
int width = img.getWidth();
int height = img.getHeight();
int area = width * height;
int gray[][] = new int[width][height];
int average = 0;// 灰度平均值
int graysum = 0;
int graymean = 0;
int grayfrontmean = 0;
int graybackmean = 0;
int pixelGray;
int front = 0;
int back = 0;
int[] pix = new int[width * height];
img.getPixels(pix, 0, width, 0, 0, width, height);
for (int i = 1; i < width; i++) { // 不算边界行和列,为避免越界
for (int j = 1; j < height; j++) {
int x = j * width + i;
int r = (pix[x] >> 16) & 0xff;
int g = (pix[x] >> 8) & 0xff;
int b = pix[x] & 0xff;
pixelGray = (int) (0.3 * r + 0.59 * g + 0.11 * b);// 计算每个坐标点的灰度
gray[i][j] = (pixelGray << 16) + (pixelGray << 8) + (pixelGray);
graysum += pixelGray;
}
}
graymean = (int) (graysum / area);// 整个图的灰度平均值
average = graymean;
for (int i = 0; i < width; i++) // 计算整个图的二值化阈值
{
for (int j = 0; j < height; j++) {
if (((gray[i][j]) & (0x0000ff)) < graymean) {
graybackmean += ((gray[i][j]) & (0x0000ff));
back++;
} else {
grayfrontmean += ((gray[i][j]) & (0x0000ff));
front++;
}
}
}
int frontvalue = (int) (grayfrontmean / front);// 前景中心
int backvalue = (int) (graybackmean / back);// 背景中心
float G[] = new float[frontvalue - backvalue + 1];// 方差数组
int s = 0;
for (int i1 = backvalue; i1 < frontvalue + 1; i1++)// 以前景中心和背景中心为区间采用大津法算法(OTSU算法)
{
back = 0;
front = 0;
grayfrontmean = 0;
graybackmean = 0;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (((gray[i][j]) & (0x0000ff)) < (i1 + 1)) {
graybackmean += ((gray[i][j]) & (0x0000ff));
back++;
} else {
grayfrontmean += ((gray[i][j]) & (0x0000ff));
front++;
}
}
}
grayfrontmean = (int) (grayfrontmean / front);
graybackmean = (int) (graybackmean / back);
G[s] = (((float) back / area) * (graybackmean - average)
* (graybackmean - average) + ((float) front / area)
* (grayfrontmean - average) * (grayfrontmean - average));
s++;
}
float max = G[0];
int index = 0;
for (int i = 1; i < frontvalue - backvalue + 1; i++) {
if (max < G[i]) {
max = G[i];
index = i;
}
}

for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int in = j * width + i;
if (((gray[i][j]) & (0x0000ff)) < (index + backvalue)) {
pix[in] = Color.rgb(0, 0, 0);
} else {
pix[in] = Color.rgb(255, 255, 255);
}
}
}

Bitmap temp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
temp.setPixels(pix, 0, width, 0, 0, width, height);
return temp;
}
public static boolean isFirstLaunchApp(Context context){
boolean result = true;
result = SPUtil.getInstance(context).getBoolean(Constants.isFirstLaunchApp, true);
return result;

}

public static void setIsFirstLaunchApp(Context applicationContext) {
SPUtil.getInstance(applicationContext).putBoolean(Constants.isFirstLaunchApp, false);
}

/**
* int 转化成double 保留两位小数
* @param price
* @return
*/
public static String saveDouble(int price){
Double prices = Double.valueOf(price);
return doubleTrans(prices);

}

public static String doubleTrans(double num){
if(Math.round(num)-num==0){
return String.valueOf((int)num/100);
}else{
DecimalFormat df = new DecimalFormat("#0.00");
double avg = num/100.0;
return df.format(avg);
}


}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: