package com.martin.simpledevelop.utils.bitmap;
import java.io.ByteArrayOutputStream;
import java.lang.ref.WeakReference;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Base64;
/**
* @Description 位图的工具类 <br>
* @File SaBitmapUtils.java
* @Package com.martin.simpledevelop.utils.bitmap
* @Date 2015年6月25日下午11:31:04
* @Author Donghongyu 1358506549@qq.com
* @Version v1.0.0
*/
public class SaBitmapUtils {
/**
* Log 输出标签
*/
public static String TAG = SaBitmapUtils.class.getName();
/**
* 通过文件路径获取到bitmap
*
* @param path
* 文件路径
* @param w
* 指定的宽
* @param h
* 指定的高
* @return
*/
public static Bitmap getBitmapFromPath(String path, int w, int h) {
BitmapFactory.Options opts = new BitmapFactory.Options();
// 设置为ture只获取图片大小
opts.inJustDecodeBounds = true;
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
// 返回为空
BitmapFactory.decodeFile(path, opts);
int width = opts.outWidth;
int height = opts.outHeight;
float scaleWidth = 0.f, scaleHeight = 0.f;
if (width > w || height > h) {
// 缩放
scaleWidth = ((float) width) / w;
scaleHeight = ((float) height) / h;
}
opts.inJustDecodeBounds = false;
float scale = Math.max(scaleWidth, scaleHeight);
opts.inSampleSize = (int) scale;
WeakReference<Bitmap> weak = new WeakReference<Bitmap>(
BitmapFactory.decodeFile(path, opts));
return Bitmap.createScaledBitmap(weak.get(), w, h, true);
}
/**
* 缩放/裁剪图片
*
* @param bm
* @param newWidth
* @param newHeight
* @return
*/
public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
// 获得图片的宽高
int width = bm.getWidth();
int height = bm.getHeight();
// 计算缩放比例
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 取得想要缩放的matrix参数
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// 得到新的图片
Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
true);
return newbm;
}
/**
* 把bitmap转换成base64加密的字符串
*
* @param bitmap
* @param bitmapQuality
* 压缩质量
* @return
*/
public static String getBase64FromBitmap(Bitmap bitmap, int bitmapQuality) {
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, bitmapQuality, bStream);
byte[] bytes = bStream.toByteArray();
return Base64.encodeToString(bytes, Base64.DEFAULT);
}
/**
* 把base64转换成bitmap
*
* @param string
* @return
*/
public static Bitmap getBitmapFromBase64(String string) {
byte[] bitmapArray = null;
try {
bitmapArray = Base64.decode(string, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
return BitmapFactory
.decodeByteArray(bitmapArray, 0, bitmapArray.length);
}
}