【问题标题】:How to convert HTML files (stored in assets) to image in android?如何将 HTML 文件(存储在资产中)转换为 android 中的图像?
【发布时间】:2016-01-26 13:13:57
【问题描述】:

我正在尝试将存储为资产的 html 文件转换为图像,以便我可以共享它们。我尝试了以下代码:

Picture picture = webView.capturePicture();
Bitmap b = Bitmap.createBitmap(
        picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);

FileOutputStream fos = null;
try {
    fos = new FileOutputStream( Environment.getExternalStorageDirectory().toString() +"/temp.jpg");
    if ( fos != null ) {
        b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        Toast.makeText(SyllabusPage_NW.this, "created", Toast.LENGTH_SHORT).show();
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        Uri screenshotUri = Uri.parse(Environment.getExternalStorageDirectory().toString() + "/temp.jpg");

        sharingIntent.setType("image/jpeg");
        sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        startActivity(Intent.createChooser(sharingIntent, "Share image using"));
        fos.close();

    }
}
catch( Exception e ) {

    Toast.makeText(SyllabusPage_NW.this, "Error", Toast.LENGTH_SHORT).show();
}

这个结果被附加了,预期的结果也被附加了。 webview 仅捕获 html 页面的第一部分。 我想知道如何捕获整个 html 页面,而不仅仅是第一个?

【问题讨论】:

  • trying to convert html files stored as assets to image。多么可怕的描述。这与资产或 webview 显示的内容有什么关系?您只想在 webview 中获得完整实际页面的图片。不仅是可见部分。
  • 建议链接中命名的 capturePicture() 方法曾经有效。但据我所知,如果您在 6.0 上运行,则不再使用新的 webkit。那么您正在为哪个 Android 版本编译?
  • “我正在尝试将存储为资产的 html 文件转换为图像”——嗯,为什么不直接打包图像?
  • @MurtazaKhursheedHussain 我尝试了同样的事情,但它不起作用。

标签: android html image image-processing webview


【解决方案1】:

对于 API Lollipop 及更高版本应启用慢速绘制:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    WebView.enableSlowWholeDocumentDraw();
}

然后通过调试检查图片高度是否正确。
如果不是先测量 webview,然后再进行布局。

webView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
webView.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
webView.buildDrawingCache(true);

Bitmap b = Bitmap.createBitmap(webView.getDrawingCache());
webView.setDrawingCacheEnabled(false);

【讨论】:

    猜你喜欢
    • 2019-08-13
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2020-07-09
    相关资源
    最近更新 更多