Android Webview 保存为图片

/**
	 * @param view, the View you want to screenshot, such as WebView, etc.
	 * @param width, screenshot's width.
	 * @param height, screenshot's height.
	 * @param scroll, true if you want to start capture from currently scroll position.
	 * @param config, the Bitmap.Config, such as ARGB_8888, etc.
	 *
	 * @return the screenshot's Bitmap
	 */
	public static Bitmap capture(View view, float width, float height, boolean scroll, Bitmap.Config config) {
	    if (!view.isDrawingCacheEnabled()) {
	        view.setDrawingCacheEnabled(true);
	    }
	    Bitmap bitmap = Bitmap.createBitmap((int) width, (int) height, config);
	    bitmap.eraseColor(Color.WHITE);
	    Canvas canvas = new Canvas(bitmap);
	    int left = view.getLeft();
	    int top = view.getTop();
	    if (scroll) {
	        left = view.getScrollX();
	        top = view.getScrollY();
	    }
	    int status = canvas.save();
	    canvas.translate(-left, -top);
	    float scale = width / view.getWidth();
	    canvas.scale(scale, scale, left, top);
	    view.draw(canvas);
	    canvas.restoreToCount(status);
	    Paint alphaPaint = new Paint();
	    alphaPaint.setColor(Color.TRANSPARENT);
	    canvas.drawRect(0f, 0f, 1f, height, alphaPaint);
	    canvas.drawRect(width - 1f, 0f, width, height, alphaPaint);
	    canvas.drawRect(0f, 0f, width, 1f, alphaPaint);
	    canvas.drawRect(0f, height - 1f, width, height, alphaPaint);
	    canvas.setBitmap(null);
	    return bitmap;
	}


public static String screenshot(Context context, Bitmap bitmap, String name) {
        if (bitmap == null) {
            return null;
        }

        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        if (name == null || name.trim().isEmpty()) {
            name = String.valueOf(System.currentTimeMillis());
        }
        name = name.trim();

        int count = 0;
        File file = new File(dir, name + ".png");
        while (file.exists()) {
            count++;
            file = new File(dir, name + "." + count + ".png");
        }

        try {
            FileOutputStream stream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            stream.flush();
            stream.close();
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
            return file.getAbsolutePath();
        } catch (Exception e) {
            return null;
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值