WebP格式是什么在这里就不再赘述,大家自行百度。 我就直接说怎么在android中将jpg、png转换成webp格式。
直接上代码:
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之前的话就要用到jni或者ndk,ndk的环境这里就不再介绍,可以去看我的另一篇博客实现PHP服务器+Android客户端(Retrofit+RxJava)第五天学一学ndk开发吧 webp参考:这里 或者这里
