首先我要说的是,加载大图片策略的描述是here。我知道有必要调整图像大小以省略OutOfMemoryError
。我想从图像中获取字节,以便能够通过Internet发送它。
public byte[] getAttachment(Context context, String fullFilePath) {
byte[] fileBytes = mFileUtil.readFileAsBytes(fullFilePath);
if (fileBytes == null) {
Logger.i("Unable to get bytes, trying through content resolver");
try {
fileBytes = mFileUtil.readFileFromContentResolver(context, fullFilePath);
} catch (OutOfMemoryError e) {
Uri imageUri = Uri.parse(fullFilePath);
if (checkIfFileIsImage(context, imageUri)) {
try {
InputStream stream = context.getContentResolver().openInputStream(imageUri);
if (stream == null) {
return null;
}
BitmapFactory.Options options = getOptions(stream, 2000, 2000);
stream.close();
stream = context.getContentResolver().openInputStream(imageUri);
if (stream == null) {
return null;
}
Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);
bitmap = rotateBitmap(context, imageUri, bitmap);
stream.close();
fileBytes = convertBitmapToArray(bitmap);
} catch (Exception e1) {
Logger.e("Unable to get bytes using fallback method, attachment " +
"will not be added");
} catch (OutOfMemoryError e2) {
Logger.e("Unable to get bytes using fallback method, because " +
"attachment is too big. Attachment will not be added");
}
}
System.gc();
}
}
return fileBytes;
}
FileUtil.class
public byte[] readFileAsBytes(String fileName) {
File originalFile = new File(fileName);
byte[] bytes = null;
try {
FileInputStream fileInputStreamReader = new FileInputStream(originalFile);
bytes = new byte[(int) originalFile.length()];
fileInputStreamReader.read(bytes);
} catch (IOException e) {
}
return bytes;
}
public byte[] readFileFromContentResolver(Context context, String fileName) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream is = null;
InputStream inputStream = null;
try {
inputStream = context.getContentResolver().openInputStream(Uri.parse(fileName));
is = new BufferedInputStream(inputStream);
byte[] data = new byte[is.available()];
is.read(data);
bos.write(data);
} catch (Exception e) {
} finally {
try {
if (is != null) {
is.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e1) {
}
}
return bos.toByteArray();
}
正如您所看到的,此代码的目的是从byte[]
获取Bitmap
,而不是here。几乎在任何情况下都可以正常工作。然而,在使用较旧的Android系统的低端设备上(但也很少),它尤其容易出错。
我不喜欢设置largeHeap
inside AndroidManifest.xml
的想法,因为这只是掩盖问题而不是应对它。我也不想发送更小的图像。
是否可以通过任何其他方式改进这段代码以摆脱OutOfMemoryError
?