压缩图片,就是把大图片压缩小,降低图片的质量,在一定范围内,降低图片的大小,并且满足需求(图片仍就清晰)。
从图片路径中读取图片(图片很大,不能全部加在到内存中处理,要是全部加载到内存中会内存溢出),我们可以以压缩的方式保存图片到手机。
public class FileUtils {
private static String mSdRootPath = null;
private static String mDataRootPath = null;
private final static String FOLDER_NAME = "/AndroidImage";
public FileUtils(Context context) {
mDataRootPath = context.getCacheDir().getPath();
mSdRootPath = Environment.getExternalStorageDirectory().getPath();
}
/**
* 获取储存Image的目录
* @return String
*/
private String getStorageDirectory() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ?
mSdRootPath + FOLDER_NAME : mDataRootPath + FOLDER_NAME;
}
/**
* 保存Image的方法,有sd卡存储到sd卡,没有就存储到手机目录
* @param fileName
* @param bitmap
* @throws IOException
*/
public void saveBitmap(String fileName, Bitmap bitmap) throws IOException {
if (bitmap == null) {
return;
}
String path = getStorageDirectory();
File folderFile = new File(path);
if (!folderFile.exists()) {
folderFile.mkdir();
}
File file = new File(path + File.separator + fileName);
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
/**
* 从手机或者sd卡获取Bitmap
* @param fileName
* @return Bitmap
*/
public Bitmap getBitmap(String fileName) {
return BitmapFactory.decodeFile(getStorageDirectory() + File.separator + fileName);
}
/**
* 获取文件的大小
* @param fileName
* @return long
*/
public long getFileSize(String fileName) {
return new File(getStorageDirectory() + File.separator + fileName).length();
}
}