WebP格式是什么在这里就不再赘述,大家自行百度。
我就直接说怎么在android中将jpg、png转换成webp格式。
4.0之后
直接上代码:
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
int h = options.outHeight;
int w = options.outWidth;
int inSampleSize = 0;
if (h > reqHeight || w > reqWidth) {
float ratioW = (float) w / reqWidth;
float ratioH = (float) h / reqHeight;
inSampleSize = (int) Math.min(ratioH, ratioW);
}
inSampleSize = Math.max(1, inSampleSize);
return inSampleSize;
}
public static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
// options.inPreferQualityOverSpeed = true;
return BitmapFactory.decodeFile(filePath, options);
}
public static byte[] compressBitmapToBytes(String filePath, int reqWidth, int reqHeight, int quality, Bitmap.CompressFormat format) {
Bitmap bitmap = getSmallBitmap(filePath, reqWidth, reqHeight);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(format, quality, baos);
byte[] bytes = baos.toByteArray();
bitmap.recycle();
Log.i(TAG, "Bitmap compressed success, size: " + bytes.length);
return bytes;
}
最后
byte[] bytes1 = BitmapUtil.compressBitmapToBytes(file.getPath(), 600, 0, 60, Bitmap.CompressFormat.WEBP);//分别是图片路径,宽度高度,质量,和图片类型,重点在这里。
File webp = new File(path, imgName + "compress.webp");
//这下面就写个大致,自己完善
FileOutputStream fos = new FileOutputStream(webp);
fos.write(bytes1 );
fos.close();
这样就实现了jpg到webp的转换。png的话也一样。
4.0之前
4.0之前的话就要用到jni或者ndk,ndk的环境这里就不再介绍,可以去看我的另一篇博客实现PHP服务器+Android客户端(Retrofit+RxJava)第五天学一学ndk开发吧
webp参考:这里
或者这里
最后讲一讲感想
- 在使用BitmapUtil.compressBitmapToBytes()的时候,如果你指定质量为100,也就是不压缩,你会发现,图片变大了。。。我曹,我已开始都怀疑人生了。这个时候不要急,慢慢一步一步跟踪,你会发现是在在文件转成bitmap的时候变大的。我这里就不深究原理的。记住要适当的降低一点质量就行。
- 相同的一张jpg图片,不管是转成png还是webp,大小都是一样的。这里我还没有进行过研究,但是我猜测转变成不同的格式之后,大小虽然都一样,但是图片的显示出来的效果应该是有差异的,逼近官网宣称:在质量相同的情况下,WebP格式图像的体积要比JPEG格式图像小40%,如果大小一样的话,质量应该是有差异的。
- 在使用ndk生成so文件的时候需要注意,可能会在生成so文件之后,你直接运行会提示找不到cpu-feature.h文件,这个时候不用管它,直接就把jni文件夹删除,就只用so文件就行了,记得把配置改一改。目前我是这么解决的,其实这个头文件应该是没有用的,不知道怎么在编译的时候不去检查这个文件。。。