Android之文件搜索工具类
/**
* @detail 搜索sdcard文件
* @param 需要进行文件搜索的目录
* @param 过滤搜索文件类型
*/
private void search(File file, String[] ext) {
if (file != null) {
if (file.isDirectory()) {
File[] listFile = file.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
search(listFile[i], ext);
}
}
} else {
String filename = file.getAbsolutePath();
for (int i = 0; i < ext.length; i++) {
if (filename.endsWith(ext[i])) {
list.add(filename);
break;
}
}
}
}
}

Android之录音工具类

/**
* 录音工具类
*
* @author rendongwei
*/
public class RecordUtil {
private static final int SAMPLE_RATE_IN_HZ = 8000;

private MediaRecorder recorder = new MediaRecorder();

// 录音的路径
private String mPath;

public RecordUtil(String path) {
mPath = path;
}

/**
* 开始录音
*
* @throws IOException
*/
public void start() throws IOException {
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
throw new IOException("SD Card is not mounted,It is " + state + ".");
}
File directory = new File(mPath).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created");
}
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setAudioSamplingRate(SAMPLE_RATE_IN_HZ);
recorder.setOutputFile(mPath);
recorder.prepare();
recorder.start();
}

/**
* 结束录音
*
* @throws IOException
*/
public void stop() throws IOException {
recorder.stop();
recorder.release();
}

/**
* 获取录音时间
*
* @return
*/
public double getAmplitude() {
if (recorder != null) {
return (recorder.getMaxAmplitude());
}
return 0;
}
}

Android之多种Bitmap效果

1. 将图片变为圆角

2. 获取缩略图图片

3. LOMO特效

4. 旧时光特效

5. 暖意特效

6. 根据饱和度、色相、亮度调整图片

7. 添加图片外边框

8. 添加内边框

9. 创建一个缩放的图片

/**
* 图片工具类
*
* @author rendongwei
*/
public class PhotoUtil {
/**
* 将图片变为圆角
*
* @param bitmap 原Bitmap图片
* @param pixels 图片圆角的弧度(单位:像素(px))
* @return 带有圆角的图片(Bitmap 类型)
*/
public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {

Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
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);
final float roundPx = pixels;

paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);

return output;
}

public static boolean saveToSDCard(Bitmap bitmap) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return false;
}
FileOutputStream fileOutputStream = null;
File file = new File("/sdcard/KaiXin/Download/");
if (!file.exists()) {
file.mkdirs();
}
String fileName = UUID.randomUUID().toString() + ".jpg";
String filePath = "/sdcard/KaiXin/Download/" + fileName;
File f = new File(filePath);
if (!f.exists()) {
try {
f.createNewFile();
fileOutputStream = new FileOutputStream(filePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
} catch (IOException e) {
return false;
} finally {
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
return false;
}
}
}
return true;
}

/**
* 保存图片到本地(JPG)
*
* @param bm 保存的图片
* @return 图片路径
*/
public static String saveToLocal(Bitmap bm) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return null;
}
FileOutputStream fileOutputStream = null;
File file = new File("/sdcard/KaiXin/Images/");
if (!file.exists()) {
file.mkdirs();
}
String fileName = UUID.randomUUID().toString() + ".jpg";
String filePath = "/sdcard/KaiXin/Images/" + fileName;
File f = new File(filePath);
if (!f.exists()) {
try {
f.createNewFile();
fileOutputStream = new FileOutputStream(filePath);
bm.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
} catch (IOException e) {
return null;
} finally {
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
return null;
}
}
}
return filePath;
}

/**
* 保存图片到本地(PNG)
*
* @param bm 保存的图片
* @return 图片路径
*/
public static String saveToLocalPNG(Bitmap bm) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return null;
}
FileOutputStream fileOutputStream = null;
File file = new File("/sdcard/KaiXin/Images/");
if (!file.exists()) {
file.mkdirs();
}
String fileName = UUID.randomUUID().toString() + ".png";
String filePath = "/sdcard/KaiXin/Images/" + fileName;
File f = new File(filePath);
if (!f.exists()) {
try {
f.createNewFile();
fileOutputStream = new FileOutputStream(filePath);
bm.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
} catch (IOException e) {
return null;
} finally {
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
return null;
}
}
}
return filePath;
}

/**
* 获取缩略图图片
*
* @param imagePath 图片的路径
* @param width 图片的宽度
* @param height 图片的高度
* @return 缩略图图片
*/
public static Bitmap getImageThumbnail(String imagePath, int width, int height) {
Bitmap bitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// 获取这个图片的宽和高,注意此处的bitmap为null
bitmap = BitmapFactory.decodeFile(imagePath, options);
options.inJustDecodeBounds = false; // 设为 false
// 计算缩放比
int h = options.outHeight;
int w = options.outWidth;
int beWidth = w / width;
int beHeight = h / height;
int be = 1;
if (beWidth < beHeight) {
be = beWidth;
} else {
be = beHeight;
}
if (be <= 0) {
be = 1;
}
options.inSampleSize = be;
// 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false
bitmap = BitmapFactory.decodeFile(imagePath, options);
// 利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个Bitmap对象
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
return bitmap;
}

/**
* LOMO特效
*
* @param bitmap 原图片
* @return LOMO特效图片
*/
public static Bitmap lomoFilter(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int dst[] = new int[width * height];
bitmap.getPixels(dst, 0, width, 0, 0, width, height);

int ratio = width > height ? height * 32768 / width : width * 32768 / height;
int cx = width >> 1;
int cy = height >> 1;
int max = cx * cx + cy * cy;
int min = (int)(max * (1 - 0.8f));
int diff = max - min;

int ri, gi, bi;
int dx, dy, distSq, v;

int R, G, B;

int value;
int pos, pixColor;
int newR, newG, newB;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
pos = y * width + x;
pixColor = dst[pos];
R = Color.red(pixColor);
G = Color.green(pixColor);
B = Color.blue(pixColor);

value = R < 128 ? R : 256 - R;
newR = (value * value * value) / 64 / 256;
newR = (R < 128 ? newR : 255 - newR);

value = G < 128 ? G : 256 - G;
newG = (value * value) / 128;
newG = (G < 128 ? newG : 255 - newG);

newB = B / 2 + 0x25;

// ==========边缘黑暗==============//
dx = cx - x;
dy = cy - y;
if (width > height)
dx = (dx * ratio) >> 15;
else
dy = (dy * ratio) >> 15;

distSq = dx * dx + dy * dy;
if (distSq > min) {
v = ((max - distSq) << 8) / diff;
v *= v;

ri = newR * v >> 16;
gi = newG * v >> 16;
bi = newB * v >> 16;

newR = ri > 255 ? 255 : (ri < 0 ? 0 : ri);
newG = gi > 255 ? 255 : (gi < 0 ? 0 : gi);
newB = bi > 255 ? 255 : (bi < 0 ? 0 : bi);
}
// ==========边缘黑暗end==============//

dst[pos] = Color.rgb(newR, newG, newB);
}
}

Bitmap acrossFlushBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
acrossFlushBitmap.setPixels(dst, 0, width, 0, 0, width, height);
return acrossFlushBitmap;
}

/**
* 旧时光特效
*
* @param bmp 原图片
* @return 旧时光特效图片
*/
public static Bitmap oldTimeFilter(Bitmap bmp) {
int width = bmp.getWidth();
int height = bmp.getHeight();
Bitmap bitmap = 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];
bmp.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;
}
}

bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}

/**
* 暖意特效
*
* @param bmp 原图片
* @param centerX 光源横坐标
* @param centerY 光源纵坐标
* @return 暖意特效图片
*/
public static Bitmap warmthFilter(Bitmap bmp, int centerX, int centerY) {
final int width = bmp.getWidth();
final int height = bmp.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 radius = Math.min(centerX, centerY);

final float strength = 150F; // 光照强度 100~150
int[] pixels = new int[width * height];
bmp.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);
}
}

bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}

/**
* 根据饱和度、色相、亮度调整图片
*
* @param bm 原图片
* @param saturation 饱和度
* @param hue 色相
* @param lum 亮度
* @return 处理后的图片
*/
public static Bitmap handleImage(Bitmap bm, int saturation, int hue, int lum) {
Bitmap bmp = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
Paint paint = new Paint();
paint.setAntiAlias(true);
ColorMatrix mLightnessMatrix = new ColorMatrix();
ColorMatrix mSaturationMatrix = new ColorMatrix();
ColorMatrix mHueMatrix = new ColorMatrix();
ColorMatrix mAllMatrix = new ColorMatrix();
float mSaturationValue = saturation * 1.0F / 127;
float mHueValue = hue * 1.0F / 127;
float mLumValue = (lum - 127) * 1.0F / 127 * 180;
mHueMatrix.reset();
mHueMatrix.setScale(mHueValue, mHueValue, mHueValue, 1);

mSaturationMatrix.reset();
mSaturationMatrix.setSaturation(mSaturationValue);
mLightnessMatrix.reset();

mLightnessMatrix.setRotate(0, mLumValue);
mLightnessMatrix.setRotate(1, mLumValue);
mLightnessMatrix.setRotate(2, mLumValue);

mAllMatrix.reset();
mAllMatrix.postConcat(mHueMatrix);
mAllMatrix.postConcat(mSaturationMatrix);
mAllMatrix.postConcat(mLightnessMatrix);

paint.setColorFilter(new ColorMatrixColorFilter(mAllMatrix));
canvas.drawBitmap(bm, 0, 0, paint);
return bmp;
}

/**
* 添加图片外边框
*
* @param context 上下文
* @param bm 原图片
* @param frameName 边框名称
* @return 带有边框的图片
*/
public static Bitmap combinateFrame(Context context, Bitmap bm, String frameName) {
// 原图片的宽高
int imageWidth = bm.getWidth();
int imageHeight = bm.getHeight();

// 边框
Bitmap leftUp = decodeBitmap(context, frameName, 0);
Bitmap leftDown = decodeBitmap(context, frameName, 2);
Bitmap rightDown = decodeBitmap(context, frameName, 4);
Bitmap rightUp = decodeBitmap(context, frameName, 6);
Bitmap top = decodeBitmap(context, frameName, 7);
Bitmap down = decodeBitmap(context, frameName, 3);
Bitmap left = decodeBitmap(context, frameName, 1);
Bitmap right = decodeBitmap(context, frameName, 5);

Bitmap newBitmap = null;
Canvas canvas = null;

// 判断大小图片的宽高
int judgeWidth = 0;
int judgeHeight = 0;
if ("frame7".equals(frameName)) {
judgeWidth = leftUp.getWidth() + rightUp.getWidth() + top.getWidth() * 5;
judgeHeight = leftUp.getHeight() + leftDown.getHeight() + left.getHeight() * 5;
} else if ("frame10".equals(frameName)) {
judgeWidth = leftUp.getWidth() + rightUp.getWidth() + top.getWidth() * 5;
judgeHeight = leftUp.getHeight() + leftDown.getHeight() + left.getHeight() * 10;
} else {
judgeWidth = leftUp.getWidth() + rightUp.getWidth() + top.getWidth();
judgeHeight = leftUp.getHeight() + leftDown.getHeight() + left.getHeight();
}
// 内边框
if (imageWidth > judgeWidth && imageHeight > judgeHeight) {
// 重新定义一个bitmap
newBitmap = Bitmap.createBitmap(imageWidth, imageHeight, Config.ARGB_8888);
canvas = new Canvas(newBitmap);
Paint paint = new Paint();
// 画原图
canvas.drawBitmap(bm, 0, 0, paint);
// 上空余宽度
int topWidth = imageWidth - leftUp.getWidth() - rightUp.getWidth();
// 上空余填充个数
int topCount = (int)Math.ceil(topWidth * 1.0f / top.getWidth());
for (int i = 0; i < topCount; i++) {
canvas.drawBitmap(top, leftUp.getWidth() + top.getWidth() * i, 0, paint);
}
// 下空余宽度
int downWidth = imageWidth - leftDown.getWidth() - rightDown.getWidth();
// 下空余填充个数
int downCount = (int)Math.ceil(downWidth * 1.0f / down.getWidth());
for (int i = 0; i < downCount; i++) {
canvas.drawBitmap(down, leftDown.getWidth() + down.getWidth() * i,
imageHeight - down.getHeight(), paint);
}
// 左空余高度
int leftHeight = imageHeight - leftUp.getHeight() - leftDown.getHeight();
// 左空余填充个数
int leftCount = (int)Math.ceil(leftHeight * 1.0f / left.getHeight());
for (int i = 0; i < leftCount; i++) {
canvas.drawBitmap(left, 0, leftUp.getHeight() + left.getHeight() * i, paint);
}
// 右空余高度
int rightHeight = imageHeight - rightUp.getHeight() - rightDown.getHeight();
// 右空余填充个数
int rightCount = (int)Math.ceil(rightHeight * 1.0f / right.getHeight());
for (int i = 0; i < rightCount; i++) {
canvas.drawBitmap(right, imageWidth - right.getWidth(),
rightUp.getHeight() + right.getHeight() * i, paint);
}
// 画左上角
canvas.drawBitmap(leftUp, 0, 0, paint);
// 画左下角
canvas.drawBitmap(leftDown, 0, imageHeight - leftDown.getHeight(), paint);
// 画右下角
canvas.drawBitmap(rightDown, imageWidth - rightDown.getWidth(),
imageHeight - rightDown.getHeight(), paint);
// 画右上角
canvas.drawBitmap(rightUp, imageWidth - rightUp.getWidth(), 0, paint);

} else {
if ("frame7".equals(frameName)) {
imageWidth = leftUp.getWidth() + top.getWidth() * 5 + rightUp.getWidth();
imageHeight = leftUp.getHeight() + left.getHeight() * 5 + leftDown.getHeight();
} else if ("frame10".equals(frameName)) {
imageWidth = leftUp.getWidth() + top.getWidth() * 5 + rightUp.getWidth();
imageHeight = leftUp.getHeight() + left.getHeight() * 10 + leftDown.getHeight();
} else {
imageWidth = leftUp.getWidth() + top.getWidth() + rightUp.getWidth();
imageHeight = leftUp.getHeight() + left.getHeight() + leftDown.getHeight();
}
newBitmap = Bitmap.createBitmap(imageWidth, imageHeight, Config.ARGB_8888);
canvas = new Canvas(newBitmap);
Paint paint = new Paint();
int newImageWidth = imageWidth - left.getWidth() - right.getWidth() + 5;
int newImageHeight = imageHeight - top.getHeight() - down.getHeight() + 5;
bm = Bitmap.createScaledBitmap(bm, newImageWidth, newImageHeight, true);
canvas.drawBitmap(bm, left.getWidth(), top.getHeight(), paint);
if ("frame7".equals(frameName)) {

for (int i = 0; i < 5; i++) {
canvas.drawBitmap(top, leftUp.getWidth() + top.getWidth() * i, 0, paint);
}

for (int i = 0; i < 5; i++) {
canvas.drawBitmap(left, 0, leftUp.getHeight() + left.getHeight() * i,
paint);
}

for (int i = 0; i < 5; i++) {
canvas.drawBitmap(right, imageWidth - right.getWidth(),
rightUp.getHeight() + right.getHeight() * i, paint);
}

for (int i = 0; i < 5; i++) {
canvas.drawBitmap(down, leftDown.getWidth() + down.getWidth() * i,
imageHeight - down.getHeight(), paint);
}
canvas.drawBitmap(leftUp, 0, 0, paint);
canvas.drawBitmap(rightUp, leftUp.getWidth() + top.getWidth() * 5, 0, paint);
canvas.drawBitmap(leftDown, 0, leftUp.getHeight() + left.getHeight() * 5,
paint);
canvas.drawBitmap(rightDown, imageWidth - rightDown.getWidth(),
rightUp.getHeight() + right.getHeight() * 5, paint);

} else if ("frame10".equals(frameName)) {
for (int i = 0; i < 5; i++) {
canvas.drawBitmap(top, leftUp.getWidth() + top.getWidth() * i, 0, paint);
}

for (int i = 0; i < 10; i++) {
canvas.drawBitmap(left, 0, leftUp.getHeight() + left.getHeight() * i,
paint);
}

for (int i = 0; i < 10; i++) {
canvas.drawBitmap(right, imageWidth - right.getWidth(),
rightUp.getHeight() + right.getHeight() * i, paint);
}

for (int i = 0; i < 5; i++) {
canvas.drawBitmap(down, leftDown.getWidth() + down.getWidth() * i,
imageHeight - down.getHeight(), paint);
}
canvas.drawBitmap(leftUp, 0, 0, paint);
canvas.drawBitmap(rightUp, leftUp.getWidth() + top.getWidth() * 5, 0, paint);
canvas.drawBitmap(leftDown, 0, leftUp.getHeight() + left.getHeight() * 10,
paint);
canvas.drawBitmap(rightDown, imageWidth - rightDown.getWidth(),
rightUp.getHeight() + right.getHeight() * 10, paint);
} else {
canvas.drawBitmap(leftUp, 0, 0, paint);
canvas.drawBitmap(top, leftUp.getWidth(), 0, paint);
canvas.drawBitmap(rightUp, leftUp.getWidth() + top.getWidth(), 0, paint);
canvas.drawBitmap(left, 0, leftUp.getHeight(), paint);
canvas.drawBitmap(leftDown, 0, leftUp.getHeight() + left.getHeight(), paint);
canvas.drawBitmap(right, imageWidth - right.getWidth(), rightUp.getHeight(),
paint);
canvas.drawBitmap(rightDown, imageWidth - rightDown.getWidth(),
rightUp.getHeight() + right.getHeight(), paint);
canvas.drawBitmap(down, leftDown.getWidth(), imageHeight - down.getHeight(),
paint);
}
}
// 回收
leftUp.recycle();
leftUp = null;
leftDown.recycle();
leftDown = null;
rightDown.recycle();
rightDown = null;
rightUp.recycle();
rightUp = null;
top.recycle();
top = null;
down.recycle();
down = null;
left.recycle();
left = null;
right.recycle();
right = null;
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
return newBitmap;
}

/**
* 获取边框图片
*
* @param context 上下文
* @param frameName 边框名称
* @param position 边框的类型
* @return 边框图片
*/
private static Bitmap decodeBitmap(Context context, String frameName, int position) {
try {
switch (position) {
case 0:
return BitmapFactory.decodeStream(
context.getAssets().open("frames/" + frameName + "/leftup.png"));
case 1:
return BitmapFactory.decodeStream(
context.getAssets().open("frames/" + frameName + "/left.png"));
case 2:
return BitmapFactory.decodeStream(
context.getAssets().open("frames/" + frameName + "/leftdown.png"));
case 3:
return BitmapFactory.decodeStream(
context.getAssets().open("frames/" + frameName + "/down.png"));
case 4:
return BitmapFactory.decodeStream(
context.getAssets().open("frames/" + frameName + "/rightdown.png"));
case 5:
return BitmapFactory.decodeStream(
context.getAssets().open("frames/" + frameName + "/right.png"));
case 6:
return BitmapFactory.decodeStream(
context.getAssets().open("frames/" + frameName + "/rightup.png"));
case 7:
return BitmapFactory.decodeStream(
context.getAssets().open("frames/" + frameName + "/up.png"));
default:
return null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

/**
* 添加内边框
*
* @param bm 原图片
* @param frame 内边框图片
* @return 带有边框的图片
*/
public static Bitmap addBigFrame(Bitmap bm, Bitmap frame) {
Bitmap newBitmap = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
Paint paint = new Paint();
canvas.drawBitmap(bm, 0, 0, paint);
frame = Bitmap.createScaledBitmap(frame, bm.getWidth(), bm.getHeight(), true);
canvas.drawBitmap(frame, 0, 0, paint);
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
return newBitmap;

}

/**
* 创建一个缩放的图片
*
* @param path 图片地址
* @param w 图片宽度
* @param h 图片高度
* @return 缩放后的图片
*/
public static Bitmap createBitmap(String path, int w, int h) {
try {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
// 这里是整个方法的关键,inJustDecodeBounds设为true时将不为图片分配内存。
BitmapFactory.decodeFile(path, opts);
int srcWidth = opts.outWidth;// 获取图片的原始宽度
int srcHeight = opts.outHeight;// 获取图片原始高度
int destWidth = 0;
int destHeight = 0;
// 缩放的比例
double ratio = 0.0;
if (srcWidth < w || srcHeight < h) {
ratio = 0.0;
destWidth = srcWidth;
destHeight = srcHeight;
} else if (srcWidth > srcHeight) {// 按比例计算缩放后的图片大小,maxLength是长或宽允许的最大长度
ratio = (double)srcWidth / w;
destWidth = w;
destHeight = (int)(srcHeight / ratio);
} else {
ratio = (double)srcHeight / h;
destHeight = h;
destWidth = (int)(srcWidth / ratio);
}
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 缩放的比例,缩放是很难按准备的比例进行缩放的,目前我只发现只能通过inSampleSize来进行缩放,其值表明缩放的倍数,SDK中建议其值是2的指数值
newOpts.inSampleSize = (int)ratio + 1;
// inJustDecodeBounds设为false表示把图片读进内存中
newOpts.inJustDecodeBounds = false;
// 设置大小,这个一般是不准确的,是以inSampleSize的为准,但是如果不设置却不能缩放
newOpts.outHeight = destHeight;
newOpts.outWidth = destWidth;
// 获取缩放后图片
return BitmapFactory.decodeFile(path, newOpts);
} catch (Exception e) {
// TODO: handle exception
return null;
}
}

public static Bitmap createBitmap2(Context context, int id, int w, int h) {
try {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
// 这里是整个方法的关键,inJustDecodeBounds设为true时将不为图片分配内存。
BitmapFactory.decodeResource(context.getResources(), id, opts);
int srcWidth = opts.outWidth;// 获取图片的原始宽度
int srcHeight = opts.outHeight;// 获取图片原始高度
int destWidth = 0;
int destHeight = 0;
// 缩放的比例
double ratio = 0.0;
if (srcWidth < w || srcHeight < h) {
ratio = 0.0;
destWidth = srcWidth;
destHeight = srcHeight;
} else if (srcWidth > srcHeight) {// 按比例计算缩放后的图片大小,maxLength是长或宽允许的最大长度
ratio = (double)srcWidth / w;
destWidth = w;
destHeight = (int)(srcHeight / ratio);
} else {
ratio = (double)srcHeight / h;
destHeight = h;
destWidth = (int)(srcWidth / ratio);
}
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 缩放的比例,缩放是很难按准备的比例进行缩放的,目前我只发现只能通过inSampleSize来进行缩放,其值表明缩放的倍数,SDK中建议其值是2的指数值
newOpts.inSampleSize = (int)ratio + 1;
// inJustDecodeBounds设为false表示把图片读进内存中
newOpts.inJustDecodeBounds = false;
// 设置大小,这个一般是不准确的,是以inSampleSize的为准,但是如果不设置却不能缩放
newOpts.outHeight = destHeight;
newOpts.outWidth = destWidth;
// 获取缩放后图片
// return BitmapFactory.decodeFile(path, newOpts);
return BitmapFactory.decodeResource(context.getResources(), id, newOpts);
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
}

Android之判断当前网络状态

/**
* 检测网络是否可用
*
* @return
*/
public boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager)getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnectedOrConnecting();
}

/**
* 获取当前网络类型
*
* @return 0:没有网络 1:WIFI网络 2:WAP网络 3:NET网络
*/

public static final int NETTYPE_WIFI = 0x01;

public static final int NETTYPE_CMWAP = 0x02;

public static final int NETTYPE_CMNET = 0x03;

public int getNetworkType() {
int netType = 0;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo == null) {
return netType;
}
int nType = networkInfo.getType();
if (nType == ConnectivityManager.TYPE_MOBILE) {
String extraInfo = networkInfo.getExtraInfo();
if (!StringUtils.isEmpty(extraInfo)) {
if (extraInfo.toLowerCase().equals("cmnet")) {
netType = NETTYPE_CMNET;
} else {
netType = NETTYPE_CMWAP;
}
}
} else if (nType == ConnectivityManager.TYPE_WIFI) {
netType = NETTYPE_WIFI;
}
return netType;
}

Android之计算两个时间的相差

/**
* 以友好的方式显示时间
*
* @param sdate
* @return
*/
public static String friendly_time(String sdate) {
Date time = toDate(sdate);
if (time == null) {
return "Unknown";
}
String ftime = "";
Calendar cal = Calendar.getInstance();

// 判断是否是同一天
String curDate = dateFormater2.get().format(cal.getTime());
String paramDate = dateFormater2.get().format(time);
if (curDate.equals(paramDate)) {
int hour = (int)((cal.getTimeInMillis() - time.getTime()) / 3600000);
if (hour == 0)
ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
else
ftime = hour + "小时前";
return ftime;
}

long lt = time.getTime() / 86400000;
long ct = cal.getTimeInMillis() / 86400000;
int days = (int)(ct - lt);
if (days == 0) {
int hour = (int)((cal.getTimeInMillis() - time.getTime()) / 3600000);
if (hour == 0)
ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
else
ftime = hour + "小时前";
} else if (days == 1) {
ftime = "昨天";
} else if (days == 2) {
ftime = "前天";
} else if (days > 2 && days <= 10) {
ftime = days + "天前";
} else if (days > 10) {
ftime = dateFormater2.get().format(time);
}
return ftime;
}

/**
* 将字符串转位日期类型
*
* @param sdate
* @return
*/
public static Date toDate(String sdate) {
try {
return dateFormater.get().parse(sdate);
} catch (ParseException e) {
return null;
}
}

private final static ThreadLocal<SimpleDateFormat> dateFormater=new ThreadLocal<SimpleDateFormat>(){@Override protected SimpleDateFormat initialValue(){return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");}};

private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};

Android之判断时间是否为今天

/**
* 判断给定字符串时间是否为今日
*
* @param sdate
* @return boolean
*/
public static boolean isToday(String sdate) {
boolean b = false;
Date time = toDate(sdate);
Date today = new Date();
if (time != null) {
String nowDate = dateFormater2.get().format(today);
String timeDate = dateFormater2.get().format(time);
if (nowDate.equals(timeDate)) {
b = true;
}
}
return b;
}

/**
* 将字符串转位日期类型
*
* @param sdate
* @return
*/
public static Date toDate(String sdate) {
try {
return dateFormater.get().parse(sdate);
} catch (ParseException e) {
return null;
}
}

private final static ThreadLocal<SimpleDateFormat> dateFormater=new ThreadLocal<SimpleDateFormat>(){@Override protected SimpleDateFormat initialValue(){return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");}};

private final static ThreadLocal<SimpleDateFormat> dateFormater2=new ThreadLocal<SimpleDateFormat>(){@Override protected SimpleDateFormat initialValue(){return new SimpleDateFormat("yyyy-MM-dd");}};

随笔分类 - Android之工具类的更多相关文章

  1. 53. Android常用工具类

    主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.Prefer ...

  2. Android 常见工具类封装

    1,MD5工具类: public class MD5Util { public final static String MD5(String s) { char hexDigits[] = { '0' ...

  3. 【转】Android常用工具类

    主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.Prefe ...

  4. Android基础工具类重构系列一Toast

    前言: 一直在考虑写一下Android实际项目中的一些总结,翻看CSDN博客,上一篇已经是一年多曾经. 本系列定位Android基础工具类重构.旨在记录实际项目中经经常使用到的一些工具类,比方Toas ...

  5. (转载)android 一些工具类汇总

    android 一些工具类汇总 作者:曾田生z 字体:[增加 减小] 类型:转载 时间:2016-08-14我要评论 本文给大家汇总介绍了一些常用的Android工具类,非常的简单实用,有需要的小伙伴 ...

  6. Android 系统工具类SystemUtils

    包含的功能有: 获取系统中所有APP应用.获取用户安装的APP应用.根据包名和Activity启动类查询应用信息.跳转到WIFI设置.WIFI网络开关.移动网络开关.GPS开关 当前若关则打开 当前若 ...

  7. Android Sqlite 工具类封装

    鉴于经常使用 Sqlite 数据库做数据持久化处理,进行了一点封装,方便使用. 该封装类主要支持一下功能 支持多用户数据储存 支持 Sqlite数据库升级 支持传入 Sql 语句建表 支持 SQLit ...

  8. Android 常用工具类之SPUtil,可以修改默认sp文件的路径

    参考: 1. 利用Java反射机制改变SharedPreferences存储路径    Singleton1900 2. Android快速开发系列 10个常用工具类 Hongyang import ...

  9. Android常见工具类封装

    MD5加密 import android.annotation.SuppressLint; import java.security.MessageDigest; public class MD5 { ...

随机推荐

  1. 对应sslocal的简易luci web界面

    直接通过官方ss代码库安装的ss, 只有一个可执行的sslocal, 也没找到对应的luci-app, 所以就自己写了一个. 因为/etc/init.d/sslocal 和 /etc/config/s ...

  2. 极路由2(极贰)在OpenWrt下定制自己的ss服务

    默认刷入的OpenWrt带的ss, 只有ss-redir服务, 但是在实际使用中, 很多时候还是希望访问直接通过正常网关, 只有少部分访问需要通过ss, 所以希望能配置成为ss-local服务. 在保 ...

  3. Spark MLlib - LFW

    val path = "/usr/data/lfw-a/*" val rdd = sc.wholeTextFiles(path) val first = rdd.first pri ...

  4. 关于mirai病毒的一些研究

    首页好像只能显示随笔,之前发在文章里面的,见文章http://www.cnblogs.com/mrchang/articles/6210681.html

  5. 【BZOJ 4579】【Usaco2016 Open】Closing the Farm

    http://www.lydsy.com/JudgeOnline/problem.php?id=4579 把时间倒过来,只是加点,并查集维护连通块. #include<cstdio> #i ...

  6. java学习笔记之线程1

    1.线程的概念 线程是系统中最小的执行单元,同一进程有多个线程,多个线程共享进程的资源. 线程调用yield()方法使线程从运行状态转入可运行状态,让出资源: 线程调用sleep()方法使线程由运行状 ...

  7. .net 项目生成时自动更新版本号

    https://www.codeproject.com/articles/31236/how-to-update-assembly-version-number-automaticall Exampl ...

  8. Leetcode 75. Sort Colors

    Given an array with n objects colored red, white or blue, sort them so that objects of the same colo ...

  9. Debian8 从本地源安装软件

    假如你从Debian官网下载了三个DVD镜像,那么就可以设置从本地源来安装软件,例如这里我从官网下载了 debian-8.6.0-amd64-DVD-1.iso,debian-8.6.0-amd64- ...

  10. mysql的优化

    1.选取最适用的字段属性 MySQL可以很好的支持大数据量的存取,但是一般说来,数据库中的表越小,在它上面执行的查询也就会越快.因此,在创建表的时候,为了获得更好的性能,我们可以将表中字段的宽度设得尽 ...