处理HTML图片适应webView和压缩图片

创建图片工具类

public class ImageUtil {

    // 调整HTML图片
    public static String adjustHTMLImage(String htmlText){
        if (htmlText == null){
            return null;
        }
        Document doc = Jsoup.parse(htmlText);
        Elements eLements = doc.getElementsByTag("img");
        for (Element element: eLements){
            // Override the width and height attribute
            element.attr("style", "display:block;width:100%;height:auto");
            // max-height:700px
        }
        return doc.toString();
    }


    // 压缩图片
    public static String compressImage(String filePath, String targetPath, int quality){
        Bitmap bm = getScaledBitmap(filePath);
        File output = new File(targetPath);
        try {
            if (!output.exists()){
                output.getParentFile().mkdir();
            } else {
                output.delete();
            }

            FileOutputStream out = new FileOutputStream(output);
            bm.compress(Bitmap.CompressFormat.JPEG, quality, out);
            out.close();
        } catch (Exception e){
            e.printStackTrace();
        }
        return output.getPath();
    }

    // 获得压缩图片
    private static Bitmap getScaledBitmap(String filePath){
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        options.inSampleSize = calculateInSampleSize(options);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    // 计算压缩尺寸
    private static int calculateInSampleSize(BitmapFactory.Options options){
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > 400 || width > 240){
            final int heightRatio = Math.round(height/ 400);
            final int widthRatio = Math.round(width/ 240);
            inSampleSize = heightRatio < width ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }
}

webView中引用

mWebView = WebView(this)
mWebView!!.loadDataWithBaseURL(null, ImageUtil.adjustHTMLImage(mArticle.content), "text/html", "charset=UTF-8", null)

上传图片压缩

File(ImageUtil.compressImage(qrCodePath, compressedImagePath, 20))
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,802评论 1 32
  • Tips 由于WebView的用法实在太多,如果您只是想查询某个功能的使用——建议Ctrl+F(Commad+F)...
    BugDev阅读 12,308评论 11 109
  • View 自定义View中在onDraw()方法中可以设置padding吗?答案是不能,设置padding后,Vi...
    ElvenShi阅读 5,902评论 0 0
  • 写手帐是因为喜欢笔记本,喜欢各种样式的笔,以及各种用途又精致的文具,而手帐能让她们之间产生链接,发生故事。 这个开...
    魔菇静阅读 3,459评论 0 3
  • 兰辛是美国密歇根州州府,冬天来得很早,往往十月底就下起雪来。 兰辛的冬天,白茫茫的。从北边来的风,呼呼地吹,吹跑了...
    ruirui0822阅读 3,365评论 0 1