【EasyExcel等比例缩小导出图片】
public static class QuotationCustomCellWriteHandler implements CellWriteHandler {
// 256分之一的字符宽度转换为标准字符宽度。
public static final int STANDARD_CHARACTER_WIDTH = 256;
// 7.5是一个估算的字符到像素的转换因子
public static final float CHARACTER_2_PIXEL_FACTOR = 7.5f;
// 将点转换为英寸,因为1点 = 1/72英寸。
public static final int PIXEL_2_INCH_FACTOR = 72;
// 英寸转换为像素,其中96是常用的DPI(每英寸像素数)值。
public static final int DPI = 96;
// 行高与像素的转换因子
public static final float ROW_HEIGHT_2_PIXEL_FACTOR = 1.3333f;
/**
* 外界传入的行高,内部查不到
*/
private final int rowHeight;
public QuotationCustomCellWriteHandler(int rowHeight) {
this.rowHeight = rowHeight;
}
@Override
public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
WriteCellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex,
Boolean isHead) {
boolean noImageValue = Objects.isNull(cellData) || cellData.getImageDataList() == null || cellData.getImageDataList().isEmpty();
if (Objects.equals(Boolean.TRUE, isHead) || noImageValue) {
return;
}
Sheet sheet = cell.getSheet();
ImageData imageData = cellData.getImageDataList().get(0);
imageData.setRelativeLastRowIndex(0);
imageData.setRelativeLastColumnIndex(0);
// 处理图像缩放 - 等比例缩放
try (ByteArrayInputStream bis = new ByteArrayInputStream(imageData.getImage())) {
BufferedImage image = ImageIO.read(bis);
int targetWidth = (int) ((double) sheet.getColumnWidth(cell.getColumnIndex()) / STANDARD_CHARACTER_WIDTH * CHARACTER_2_PIXEL_FACTOR);
int targetHeight = (int) (rowHeight * 1.0 / PIXEL_2_INCH_FACTOR * DPI);
// 计算图像的缩放比例
double scaleX = (double) targetWidth / image.getWidth();
double scaleY = (double) targetHeight / image.getHeight();
double scale = Math.min(scaleX, scaleY);
// 计算缩放后的图像大小
int scaledWidth = (int) (image.getWidth() * scale);
int scaledHeight = (int) (image.getHeight() * scale);
// 计算上下左右四个角的空白
int topPadding = (targetHeight - scaledHeight) / 2;
int bottomPadding = targetHeight - scaledHeight - topPadding;
int leftPadding = (targetWidth - scaledWidth) / 2;
int rightPadding = targetWidth - scaledWidth - leftPadding;
// 行高(点)= 像素高度 / 1.3333
imageData.setTop((int) (topPadding / ROW_HEIGHT_2_PIXEL_FACTOR));
imageData.setBottom((int) (bottomPadding / ROW_HEIGHT_2_PIXEL_FACTOR));
imageData.setLeft((int) (leftPadding / ROW_HEIGHT_2_PIXEL_FACTOR));
imageData.setRight((int) (rightPadding / ROW_HEIGHT_2_PIXEL_FACTOR));
} catch (Exception e) {
log.error("QuotationCustomCellWriteHandler afterCellDataConverted err", e);
}
CellWriteHandler.super.afterCellDataConverted(writeSheetHolder, writeTableHolder, cellData, cell, head, relativeRowIndex, isHead);
}
}