我正在将html数据加载到webview中,之后我需要捕获webview数据并将该图像存储到SD卡中。它适用于小图像,但它为大图像提供了内存不足的例外。我使用以下逻辑来做到这一点。
private void generateImg() {
// TODO Auto-generated method stub
try{
Picture p = webview.capturePicture();
Bitmap bitmap=pictureDrawable2Bitmap(p);
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString();
File myDir = new File(root + "/Aack");
if(myDir.exists())
{
//Log.e("Directory","Existed");
}
else
{
myDir.mkdir();
}
String fname = System.currentTimeMillis()+".png";
//Log.e("file name...",""+fname);
file = new File (myDir, fname);
try
{
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
file_name=myDir+"/"+fname;
}catch(Exception e)
{
e.printStackTrace();
}
}
private static Bitmap pictureDrawable2Bitmap(Picture picture){
PictureDrawable pictureDrawable = new PictureDrawable(picture);
Bitmap bitmap = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(),pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(pictureDrawable.getPicture());
return bitmap;
}
所以,请指导我如何处理这个问题。谢谢
答案 0 :(得分:0)
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int stretch_width = Math.round((float)width / (float)reqWidth);
int stretch_height = Math.round((float)height / (float)reqHeight);
if (stretch_width <= stretch_height) return stretch_height;
else return stretch_width;
}
我不知道如何在你的特殊情况下从图片到位图这样做,所以如果其他人知道可以随意编辑这篇文章。