創(chuàng)建圖片工具類
public class ImageUtil {
// 調(diào)整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);
}
// 計(jì)算壓縮尺寸
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))