美文网首页
处理HTML图片适应webView和压缩图片

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

作者: PeterWu丷 | 来源:发表于2019-05-31 09:22 被阅读0次

    创建图片工具类

    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))
    

    相关文章

      网友评论

          本文标题:处理HTML图片适应webView和压缩图片

          本文链接:https://www.haomeiwen.com/subject/kaiitctx.html