为了减少这个问题,您可以做的一件事是调整图像的大小,然后将其保存到内存中。
下面是有帮助的代码。你可以试试下面的方法。
// 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 中是否有可用空间,并根据可用空间将图像保存到 sdcard。我已经使用以下方法来获取可用的可用空间。
/**
* 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.
}