我想在sd卡中保存位图图像,我可以保存它但是有一段时间我的活动因为ram而被杀死。
所以我可以将图像保存在块中而不是以字节数组的形式保存。
我的代码如下:
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temp.jpg");
if (f.exists()) {
f.delete();
}
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:1)
解决此问题的最佳方法是将图像的大小缩小到所需的视图大小,并在后台线程(异步任务)上完成所有繁重的工作,当您的后台线程正常工作时,您可以显示任何虚拟图像表单资源,一旦图像正确处理,请用前一个替换您的位图。
在您继续阅读本文之前
Displaying Bitmaps Efficiently
Processing Bitmaps Off the UI Thread
答案 1 :(得分:1)
要减少此问题,您可以做的一件事是重新调整图像的大小,然后将其保存到内存中。
以下是有用的代码。您可以尝试以下方法。
// decodes image and scales it to reduce memory consumption public static Bitmap decodeFile(File p_f) { try { // decode image size BitmapFactory.Options m_opt = new BitmapFactory.Options(); m_opt.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(p_f), null, m_opt); // Find the correct scale value. It should be the power of 2. final int REQUIRED_SIZE = 70; int m_widthTmp = m_opt.outWidth, m_heightTmp = m_opt.outHeight; int m_scale = 1; while (true) { if (m_widthTmp / 2 < REQUIRED_SIZE || m_heightTmp / 2 < REQUIRED_SIZE) break; m_widthTmp /= 2; m_heightTmp /= 2; m_scale *= 2; } // decode with inSampleSize BitmapFactory.Options m_o2 = new BitmapFactory.Options(); m_o2.inSampleSize = m_scale; return BitmapFactory.decodeStream(new FileInputStream(p_f), null, m_o2); } catch (FileNotFoundException p_e) { } return null; }
<强>编辑:强>
您还可以检查sdcard中是否有可用空间,并根据可用空间将图像保存到SD卡中。我使用下面的方法来获得可用的空闲空间。
/** * This function find outs the free space for the given path. * * @return Bytes. Number of free space in bytes. */ public static long getFreeSpace() { try { if (Environment.getExternalStorageDirectory() != null && Environment.getExternalStorageDirectory().getPath() != null) { StatFs m_stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); long m_blockSize = m_stat.getBlockSize(); long m_availableBlocks = m_stat.getAvailableBlocks(); return (m_availableBlocks * m_blockSize); } else { return 0; } } catch (Exception e) { e.printStackTrace(); return 0; } }
使用以上内容:
if (fileSize <= getFreeSpace()) { //write your code to save the image into the sdcard. } else { //provide message that there is no more space available. }