在使用Google MlKit时,可能遇到以下问题:
implementation 'com.google.firebase:firebase-ml-vision'
implementation 'com.google.firebase:firebase-ml-vision-image-label-model'
MlKit的某些功能需要连接网络。如果设备没有连接网络,会导致出现无法识别的情况。因此,在使用MlKit时,请检查设备是否连接网络。
在处理大量图片时,可能会发生OutOfMemoryError错误。解决方法是使用图片缩放技术来降低内存占用。以下代码演示了如何使用InSampleSize来缩放图片:
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// 获得BitmapFactory.Options对象,并设置inJustDecodeBounds为true,这样可以让Android系统不真正加载图片,而是只是获取图片的原始宽高信息。
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// 计算采样率inSampleSize。
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// 设置inJustDecodeBounds为false,并使用BitmapFactory.decodeResource()方法加载真正的Bitmap对象。
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, 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;
// 如果原始图片的宽度或高度大于需要的宽度或高度,则计算出采样率inSampleSize。
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}