前言
在Android 开发 时,在UI上显示 图片时,如果用原图显示,就会占用内存,加载慢等情况。如果把图片压缩后再显示,会快很多。这样就用到了图片压缩方法。
图片压缩:
/**
* 图片压缩
* @param filePath
* @return
*/
public static Bitmap convertIconToBitmap(String filePath){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(options, 480, 800);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
if (bitmap ==null){
return null;
}
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 40, bos);
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 设置 压缩图片大小
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
private static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
}
return inSampleSize;
}
如果要实现 图片保存到数据库,就不能像保存到本地那样 直接保存。这时,需要先转换为字符串,再用字符串保存到数据库。在需要时,再从数据库读取,再转换为 Bitmap 到UI 显示。
代码如下:
/**
* Bitmap convert to String.
* @param bitmap
* @return
*/
public static String convertIconToString(Bitmap bitmap){
String bitmapStr = "";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] bytes = bos.toByteArray();
bitmapStr = Base64.encodeToString(bytes, Base64.DEFAULT);
return bitmapStr;
}
/**
* String convert to Bitmap.
* @param str
* @return
*/
public static Bitmap convertStringToIcon(String str){
Bitmap bitmap = null;
byte[] bytes;
try{
bytes = Base64.decode(str, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}catch (Exception e){
e.printStackTrace();
}
return bitmap;
}
后记:这里只是实现了,Bitmap 与 字符串直接的互转。至于怎么 保存到数据库与读取操作就自己实现了哈o( ̄▽ ̄)d~
参考资料:
http://blog.csdn.net/luhuajcdd/article/details/8948261