Browse Source

add stroke method

Looly 5 years ago
parent
commit
09d2591fa3

+ 2 - 1
CHANGELOG.md

@@ -3,7 +3,7 @@
 
 -------------------------------------------------------------------------------------------------------------
 
-# 5.4.1 (2020-08-28)
+# 5.4.1 (2020-08-29)
 
 ### 新特性
 * 【core  】     StrUtil增加firstNonXXX方法(issue#1020@Github)
@@ -20,6 +20,7 @@
 * 【core  】     StrUtil.wrapAll方法不明确修改改为wrapAllWithPair(issue#1042@Github)
 * 【core  】     EnumUtil.getEnumAt负数返回null(pr#167@Gitee)
 * 【core  】     ChineseDate增加天干地支和转换为公历方法(pr#169@Gitee)
+* 【core  】     Img增加stroke描边方法(issue#1033@Github)
 
 ### Bug修复#
 * 【poi   】     修复ExcelBase.isXlsx方法判断问题(issue#I1S502@Gitee)

+ 41 - 0
hutool-core/src/main/java/cn/hutool/core/img/Img.java

@@ -13,6 +13,7 @@ import javax.imageio.ImageIO;
 import javax.imageio.stream.ImageInputStream;
 import javax.imageio.stream.ImageOutputStream;
 import java.awt.AlphaComposite;
+import java.awt.BasicStroke;
 import java.awt.Color;
 import java.awt.Font;
 import java.awt.Graphics2D;
@@ -20,6 +21,7 @@ import java.awt.Image;
 import java.awt.Point;
 import java.awt.Rectangle;
 import java.awt.RenderingHints;
+import java.awt.Stroke;
 import java.awt.Toolkit;
 import java.awt.color.ColorSpace;
 import java.awt.geom.AffineTransform;
@@ -554,6 +556,45 @@ public class Img implements Serializable {
 		return this;
 	}
 
+	/**
+	 * 描边,此方法为向内描边,会覆盖图片相应的位置
+	 *
+	 * @param color 描边颜色,默认黑色
+	 * @param width 边框粗细
+	 * @return this
+	 * @since 5.4.1
+	 */
+	public Img stroke(Color color, float width){
+		return stroke(color, new BasicStroke(width));
+	}
+
+	/**
+	 * 描边,此方法为向内描边,会覆盖图片相应的位置
+	 *
+	 * @param color 描边颜色,默认黑色
+	 * @param stroke 描边属性,包括粗细、线条类型等,见{@link BasicStroke}
+	 * @return this
+	 * @since 5.4.1
+	 */
+	public Img stroke(Color color, Stroke stroke){
+		final BufferedImage image = ImgUtil.toBufferedImage(getValidSrcImg());
+		int width = image.getWidth(null);
+		int height = image.getHeight(null);
+		Graphics2D g = image.createGraphics();
+
+		g.setColor(ObjectUtil.defaultIfNull(color, Color.BLACK));
+		if(null != stroke){
+			g.setStroke(stroke);
+		}
+
+		g.drawRect(0, 0, width -1 , height - 1);
+
+		g.dispose();
+		this.targetImage = image;
+
+		return this;
+	}
+
 	// ----------------------------------------------------------------------------------------------------------------- Write
 
 	/**

+ 8 - 0
hutool-core/src/test/java/cn/hutool/core/img/ImgTest.java

@@ -55,4 +55,12 @@ public class ImgTest {
 				.pressImage(ImgUtil.read("d:/test/617180969474805871.jpg"), new Rectangle(0, 0, 800, 800), 1f)
 				.write(FileUtil.file("d:/test/pressImg_result.jpg"));
 	}
+
+	@Test
+	@Ignore
+	public void strokeTest(){
+		Img.from(FileUtil.file("d:/test/公章3.png"))
+				.stroke(null, 2f)
+				.write(FileUtil.file("d:/test/stroke_result.png"));
+	}
 }