/**
* 图片处理工具类
*/
public class BitMapUtils {
/**
* 对指定路径图片压缩改变其文件大小
* @param file
* @param bitmap
*/
public static void compression(File file,Bitmap bitmap){
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//第一个参数
bitmap.compress(Bitmap.CompressFormat.JPEG, 30, bos);
try {
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @param file
* @return 获取file文件大小
* @throws Exception
*/
public static long getFileSize(File file) throws Exception {
long size = 0;
if (file.exists()) {
FileInputStream fis = null;
fis = new FileInputStream(file);
size = fis.available();
} else {
file.createNewFile();
Log.e("获取文件大小", "文件不存在!");
}
return size;
}
/**
* 根据图片路劲压缩返回bitmap
* @param srcPath
* @return
*/
public static Bitmap compressImageFromFile(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = true;//只读边,不读内容
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
newOpts.inJustDecodeBounds = false;
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 = Bitmap.Config.ARGB_8888;//该模式是默认的,可不设
newOpts.inPurgeable = true;// 同时设置才会有效
newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
// return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
//其实是无效的,大家尽管尝试
return bitmap;
}
/**
* 获取bitmap所占内存大小不同于文件大小后者是流的形式
* @param bitmap
* @return
*/
public static int getBitmapSize(Bitmap bitmap){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){ //API 19
return bitmap.getAllocationByteCount();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1){//API 12
return bitmap.getByteCount();
}
return bitmap.getRowBytes() * bitmap.getHeight(); //earlier version
}
/**
* bitmap转为文件保存返回file文件
* @param bitmap
* @param filepath
* @return
*/
public static File saveBitmapFile(Bitmap bitmap, String filepath){
File file=new File(filepath);//将要保存图片的路径
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
}
一个图片处理工具类
最新推荐文章于 2022-11-30 20:28:30 发布