Android 图片压缩
2016-07-18 18:50
399 查看
/*
*此方法本人用在项目里面,压缩出来的图片清晰度还可以,
*/
private String compressionBitmap(String path){// path 是传入需要压缩图片的路径
String pa = null;
try {
File f = new File(path);
Bitmap bm = ImageTools.getSmallBitmap(path);
*此方法本人用在项目里面,压缩出来的图片清晰度还可以,
*/
private String compressionBitmap(String path){// path 是传入需要压缩图片的路径
String pa = null;
try {
File f = new File(path);
Bitmap bm = ImageTools.getSmallBitmap(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); FileOutputStream fos = new FileOutputStream(new File(ImageTools.getAlbumDir(), "small01_" + f.getName())); int options = 100; // 如果大于80kb则再次压缩,最多压缩三次 while (baos.toByteArray().length / 1024 > 80 && options != 10) { baos.reset(); bm.compress(Bitmap.CompressFormat.JPEG, options, baos); options -= 30; } fos.write(baos.toByteArray()); fos.close(); baos.close(); pa = "/mnt/sdcard/doucheng_bitmap/"+"small01_"+f.getName(); } catch (Exception e) { e.printStackTrace(); } return pa;// pa 是压缩图片后图片的路径 } // 根据路径获得图片并压缩返回bitmap public static Bitmap getSmallBitmap(String filePath) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); options.inSampleSize = calculateInSampleSize(options, 480, 800); options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(filePath, options); } // 计算图片的缩放值 public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } // 压缩后图片的路径 public static File getAlbumDir() { File dir = new File("/mnt/sdcard/doucheng_bitmap/"); if (!dir.exists()) { dir.mkdirs(); } return dir; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories