Drawing2D工具类写入图片
This commit is contained in:
1 parent
f405da26b4
commit
3bab33f7d8
3 files changed
+67
-15
No files matched your search
+37
-1
@@ -1,5 +1,7 @@
|
||||
package com.bsd.pjcloud.hard.api.utils;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
@@ -8,6 +10,7 @@ import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
@Slf4j
|
||||
public class Drawing2D {
|
||||
|
||||
/**
|
||||
@@ -26,8 +29,13 @@ public class Drawing2D {
|
||||
private final int canvasHeight = 200;
|
||||
|
||||
private int currentWidth = canvasWidth;
|
||||
|
||||
private int currentHeight = canvasHeight;
|
||||
|
||||
private final int canvasImageWidth = 300;
|
||||
|
||||
private final int canvasImageHeight = 300;
|
||||
|
||||
private final int horizontalPadding = 20;
|
||||
|
||||
private final String fontFamily = "黑体";
|
||||
@@ -92,7 +100,8 @@ public class Drawing2D {
|
||||
textPadding();
|
||||
computedLineHeight();
|
||||
Point point = centerPosition(str);
|
||||
graphics.drawString(str, point.x, getCurrentY());
|
||||
int y = getCurrentY();
|
||||
graphics.drawString(str, point.x, y);
|
||||
textPadding();
|
||||
return this;
|
||||
}
|
||||
@@ -144,6 +153,27 @@ public class Drawing2D {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Drawing2D drawImage(InputStream inputStream) {
|
||||
try {
|
||||
BufferedImage image = ImageIO.read(inputStream);
|
||||
if (image == null) return this;
|
||||
// 获取图片的原始宽度和高度
|
||||
int originalWidth = image.getWidth();
|
||||
int originalHeight = image.getHeight();
|
||||
// 计算缩放比例,确保宽度不超过 canvasImageWidth
|
||||
double scaleFactor = Math.min(1.0, (double) canvasImageWidth / originalWidth);
|
||||
int scaledWidth = (int) (originalWidth * scaleFactor);
|
||||
int scaledHeight = (int) (originalHeight * scaleFactor);
|
||||
Point point = centerPosition(new Point(scaledWidth, scaledHeight));
|
||||
currentY += scaledHeight;
|
||||
computedHeight();
|
||||
graphics.drawImage(image, point.x, point.y, scaledWidth, scaledHeight, null);
|
||||
} catch (Exception e) {
|
||||
log.error("绘制图片错误error:|{}|task:|{}|", e.getMessage(), e.getStackTrace());
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public InputStream getInputStream() throws IOException {
|
||||
drawingWhiteSide();
|
||||
graphics.dispose();
|
||||
@@ -178,6 +208,12 @@ public class Drawing2D {
|
||||
return new Point(x, y);
|
||||
}
|
||||
|
||||
private Point centerPosition(Point point) {
|
||||
// 中心X坐标
|
||||
int x = (canvasWidth - point.x) / 2;
|
||||
return new Point(x, currentY);
|
||||
}
|
||||
|
||||
private void drawingWhiteSide() {
|
||||
int borderSize = 15;
|
||||
BufferedImage borderedCanvas = new BufferedImage(currentWidth + borderSize * 2, currentHeight + borderSize * 2, BufferedImage.TYPE_INT_RGB);
|
||||
|
||||
Reference in new issue
Block a user