刚完成一个小demo,记录下压缩图片的处理步骤
技术点网上很多,大同小异,根据情况再修改
1、按图片比例压缩:获取BitmapFactory.Options对象的inSampleSize,缩放比例
public static Bitmap getimage(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
newOpts.inPreferredConfig = Bitmap.Config.ARGB_8888;
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
float hh = 800f;
float ww = 640f;
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;//设置缩放比例
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
//这里调用质量压缩
return compressImage(bitmap);
}
//看情况使用 根据bitmap
public static Bitmap comp(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
if (baos.toByteArray().length / 1024 > 1024) {//避免OOM
baos.reset();//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, 50, baos);
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
newOpts.inPreferredConfig = Bitmap.Config.ARGB_8888;
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
float hh = 800f;//这里设置高度为800f
float ww = 640f;//这里设置宽度为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;
Log.e(LOG_TAG, "be=" + be);
newOpts.inSampleSize = be;//设置缩放比例
isBm = new ByteArrayInputStream(baos.toByteArray());
bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
return compressImage(bitmap);
}
2、按质量压缩:Bitmap对象的compress方法
private static Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int options = 100;//初始值和最小值看情况修改
while (baos.toByteArray().length / 1024 > 100 && options != 10) {
options -= 10;
baos.reset();
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
return bitmap;
}
3、调用jpeglib库进行压缩,我是找到被人写好的直接用,问题多多,自己记录下简单的步骤
/**
* 我是在AS下写的,网上能找到eclipse版本的,找了很多文章说jni编程修改build.gradle文件
* 改这个改那个,结果发现也不用了,估摸是因为这是别人编译好的吧
*1.在mina目录下建jniLibs文件夹,导入so文件
*2.在app目录下建立jni目录,导入相关c文件
*3.在java目录下建net.bither.util目录,导入调用c的NativeUtil文件
*压缩完成了,但是总感觉效果不理想,图片不清楚,头一回写东西希望看到的大神不吝赐教
*/
eclipse下编译过的jpeglib库
一个相机的开源项目,感觉很强大
为啥我这个代码部分是黑白的,别人都是彩色的啊,