处理HTML图片适应webView和压缩图片
2019-05-31 本文已影响0人
PeterWu丷
创建图片工具类
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))