一、效果图
二、代码
import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Transparency; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import org.junit.Test; import sun.font.FontDesignMetrics; /** * @author 作者 ki16: * @version 创建时间:2021年6月19日 下午3:28:33 * */ public class TestUrl { public static void main(String[] args) throws Exception { tes(); } public static void tes() throws Exception { String qrUrl ="D:/soft/apache-tomcat-7.0.94-windows-x64/apache-tomcat-7.0.94/qrcode/images/295.png"; //项目地址 String relativelyPath=System.getProperty( "user.dir" ); String bgPath = relativelyPath + "/src/main/webapp/images/background.png"; // 背景图 BufferedImage bgBuffer = new BufferedImage(750, 1230, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = (Graphics2D) bgBuffer.getGraphics(); Color dd = new Color(242, 241, 246); // 黑色 g2.setBackground(dd);//设置背景色 g2.clearRect(0, 0, 750, 1230);//通过使用当前绘图表面的背景色进行填充来清除指定的矩形。 g2.setPaint(Color.WHITE);//设置画笔,设置Paint属性 g2.dispose(); Color black = new Color(0, 0, 0); // 黑色 Color grey = new Color(155, 155, 155); // 灰色 Color red = new Color(255, 0, 0); // 红色 String tips = "广州xxx旗舰店"; // 添加提示语(设置子图居中) BufferedImage imgWithTips = addTxtAtXy(bgBuffer, tips, 120, new Font("宋体", Font.BOLD, 35), black); //BufferedImage imgWithTips = addTxtAtXy(bgBuffer, tips, 180, 160, new Font("宋体", Font.PLAIN, 35), black); //推荐 String recommend = "来自:ki16的推荐"; BufferedImage recommendBufferedImage = addTxtAtXy(imgWithTips, recommend, 180, new Font("宋体", Font.BOLD, 23), grey); //商品图片合成 String pho = "http://xcx.fxsoft88.com:2019/uploadimages/goods/thumbnail/1618816956338.jpg"; BufferedImage goodsUrl = ImageIO.read(new URL(pho)); BufferedImage bufferedImage = resizeByWidth(goodsUrl, 600); BufferedImage bufferedImage1 = synthesisPicAtXy(recommendBufferedImage, bufferedImage, 75, 250); //矩形 BufferedImage rectangle = new BufferedImage(600, 280, BufferedImage.TYPE_INT_RGB); Graphics2D gRectangle = (Graphics2D) rectangle.getGraphics(); gRectangle.setBackground(Color.white);//设置背景色 gRectangle.clearRect(0, 0, 600, 280);//通过使用当前绘图表面的背景色进行填充来清除指定的矩形。 gRectangle.setPaint(Color.WHITE);//设置画笔,设置Paint属性 gRectangle.dispose(); BufferedImage bufferedImage2 = synthesisPicAtXy1(bufferedImage1, rectangle, 75, 850); String price = "¥298"; //合成价格 BufferedImage priceBufferedImage = addTxtAtXy(bufferedImage2, price, 120,970, new Font("宋体", Font.BOLD, 50), red); //合成商品名 String goodsName = "女网鞋"; BufferedImage goodsNameBufferedImage = addTxtAtXy(priceBufferedImage, goodsName, 120, 1070, new Font("宋体", Font.BOLD, 30), grey); //小程序码 BufferedImage qrcodeBuffer = ImageIO.read(new File(qrUrl)); // 小程序码缩放 BufferedImage qrcodeMinBuffer = resizeByWidth(qrcodeBuffer, 170); // 小程序码合成 BufferedImage imgWithQrcode = synthesisPicAtXy1(goodsNameBufferedImage, qrcodeMinBuffer, 480, 890); ImageIO.write(imgWithQrcode, "jpg", new File("D:/soft/apache-tomcat-7.0.94-windows-x64/apache-tomcat-7.0.94/qrcode/images/3.png")); } /** * 生成企业微信导购二维码 * @param savePath 保存地址 * @param qrCodeBuffer 二维码 * @param logo * @throws Exception */ public static void qyCode(File savePath, BufferedImage qrCodeBuffer, String logo) throws Exception{ double width = qrCodeBuffer.getWidth();// 图片宽度 double height = qrCodeBuffer.getHeight();// 图片高度 BufferedImage bufferedImage = resizeByWidth(qrCodeBuffer, width, height); BufferedImage logoBuffer = ImageIO.read(new URL(logo)); BufferedImage logoMinBuffer = resizeByWidth(logoBuffer, 120); BufferedImage imgWithQrcode = synthesisPicAtXy(bufferedImage, logoMinBuffer, (int)(width - 120)/2, ((int)(height-120)/2)); // 保存图片 ImageIO.write(imgWithQrcode, "png", savePath); } /** * 生成礼包分享海报 * @param saveFile 存储路径 * @param qrcodeImg 二维码图片 * @param bgPath 背景图片 * @throws Exception */ public static void generateSharePoster(File saveFile, String qrcodeImg, String bgPath) throws Exception { System.out.println("qrcodeImg = " + qrcodeImg); System.out.println("bgPath = " + bgPath); // 背景图 BufferedImage bgBuffer = ImageIO.read(new URL(bgPath)); // 小程序码 BufferedImage qrcodeBuffer = ImageIO.read(new File(qrcodeImg)); // 小程序码缩放 BufferedImage qrcodeMinBuffer = resizeByWidth(qrcodeBuffer, 180); // 小程序码合成 BufferedImage imgWithQrcode = synthesisPicAtXy(bgBuffer, qrcodeMinBuffer, 386, 1100); // 保存图片 ImageIO.write(imgWithQrcode, "png", saveFile); } /** * * @param bgBuffer 背景图片 * @param photoUrl 头像 * @param qrcode 小程序码 * @param nickname 昵称 * @return * @throws IOException */ public static BufferedImage generateInviteQrcode(BufferedImage bgBuffer, String photoUrl, BufferedImage qrcode, String nickname) throws IOException { String tips1 = "合伙人招募计划"; String tips2 = "高达10%-25%佣金返现"; String tips3 = "欢迎加入我们"; double width = bgBuffer.getWidth(); double height = bgBuffer.getHeight(); Color black = new Color(0, 0, 0); BufferedImage bufferedImage = resizeByWidth(bgBuffer, width, height); BufferedImage read = ImageIO.read(new URL(photoUrl)); BufferedImage avatarMinRoundBuffer = roundImage(resizeByHeight(read, 80), 80, 80); BufferedImage bufferedImage2 = synthesisPicAtXy(bufferedImage, avatarMinRoundBuffer, (int)(width - 80)/2, (int)(height*0.2)); BufferedImage imgWithTips = addTxtAtXy(bufferedImage2, nickname, ((int)(height*0.2) + 105), new Font("宋体", Font.PLAIN, 20), black); BufferedImage imgWithTips1 = addTxtAtXy(imgWithTips, tips1, ((int)(height*0.2) + 140), new Font("宋体", Font.BOLD, 26), black); BufferedImage qrcodeMinBuffer = resizeByWidth(qrcode, 100); BufferedImage imgWithQrcode = synthesisPicAtXy(imgWithTips1, qrcodeMinBuffer, (int)(width - 100)/2, ((int)(height*0.2) + 160)); BufferedImage imgWithTips2 = addTxtAtXy(imgWithQrcode, tips2, ((int)(height*0.2) + 300), new Font("宋体", Font.PLAIN, 20), black); BufferedImage imgWithTips3 = addTxtAtXy(imgWithTips2, tips3, ((int)(height*0.2) + 325), new Font("宋体", Font.PLAIN, 18), black); return imgWithTips3; } /** * 生成商品分享的海报 * @param savePath 商品保存的地址 * @param title 商品的标题 * @param user 用户名 * @param name 商品名 * @param photourl 商品地址 * @param price 商品价格 * @param qrUrl 二维码地址 * @param company 公司名 * @throws Exception */ public static void generateShareGoods(String savePath, String title, String user, String name, String photourl, String price, String qrUrl, String company) throws Exception{ //String qrUrl ="D:/soft/apache-tomcat-7.0.94-windows-x64/apache-tomcat-7.0.94/qrcode/images/295.png"; //项目地址 String relativelyPath=System.getProperty( "user.dir" ); String bgPath = relativelyPath + "/src/main/webapp/images/background.png"; // 背景图 BufferedImage bgBuffer = new BufferedImage(750, 1230, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = (Graphics2D) bgBuffer.getGraphics(); Color dd = new Color(242, 241, 246); // 黑色 g2.setBackground(dd);//设置背景色 g2.clearRect(0, 0, 750, 1230);//通过使用当前绘图表面的背景色进行填充来清除指定的矩形。 g2.setPaint(Color.WHITE);//设置画笔,设置Paint属性 g2.dispose(); Color black = new Color(0, 0, 0); // 黑色 Color grey = new Color(155, 155, 155); // 灰色 Color red = new Color(255, 0, 0); // 红色 String tips = company; // 添加提示语(设置子图居中) //tips = "小程序标题"; BufferedImage imgWithTips = addTxtAtXy(bgBuffer, tips, 120, new Font("宋体", Font.BOLD, 35), black); //BufferedImage imgWithTips = addTxtAtXy(bgBuffer, tips, 180, 160, new Font("宋体", Font.PLAIN, 35), black); //推荐 String recommend = "来自:"+ user +"的推荐"; BufferedImage recommendBufferedImage = addTxtAtXy(imgWithTips, recommend, 180, new Font("宋体", Font.BOLD, 23), grey); //商品图片合成 BufferedImage goodsUrl = ImageIO.read(new URL(photourl)); BufferedImage bufferedImage = resizeByWidth(goodsUrl, 600); BufferedImage bufferedImage1 = synthesisPicAtXy(recommendBufferedImage, bufferedImage, 75, 250); //矩形 BufferedImage rectangle = new BufferedImage(600, 280, BufferedImage.TYPE_INT_RGB); Graphics2D gRectangle = (Graphics2D) rectangle.getGraphics(); gRectangle.setBackground(Color.white);//设置背景色 gRectangle.clearRect(0, 0, 600, 280);//通过使用当前绘图表面的背景色进行填充来清除指定的矩形。 gRectangle.setPaint(Color.WHITE);//设置画笔,设置Paint属性 gRectangle.dispose(); BufferedImage bufferedImage2 = synthesisPicAtXy1(bufferedImage1, rectangle, 75, 850); price = "¥" + price; //合成价格 BufferedImage priceBufferedImage = addTxtAtXy(bufferedImage2, price, 120,970, new Font("宋体", Font.BOLD, 50), red); //合成商品名 String goodsName = "女网鞋"; BufferedImage goodsNameBufferedImage = addTxtAtXy(priceBufferedImage, goodsName, 120, 1070, new Font("宋体", Font.BOLD, 30), grey); //小程序码 BufferedImage qrcodeBuffer = ImageIO.read(new URL(qrUrl)); // 小程序码缩放 BufferedImage qrcodeMinBuffer = resizeByWidth(qrcodeBuffer, 170); // 小程序码合成 BufferedImage imgWithQrcode = synthesisPicAtXy1(goodsNameBufferedImage, qrcodeMinBuffer, 480, 890); File saveFile = new File(savePath); // 判断这个文件(saveFile)是否存在 if (!saveFile.getParentFile().exists()) { // 如果不存在就创建这个文件夹 saveFile.getParentFile().mkdirs(); } System.out.println("=============下载图片============="); ImageIO.write(imgWithQrcode, "jpg", new File(savePath)); } /** * 将第二张图片放到第一张的指定位置 * * @param imageFirst * @param imageSecond * @param x * @param y */ public static BufferedImage synthesisPicAtXy1(BufferedImage imageFirst, BufferedImage imageSecond, int x, int y) { BufferedImage image = null; try { /* 读取第一张图片 宽高 */ int width = imageFirst.getWidth();// 图片宽度 int height = imageFirst.getHeight();// 图片高度 /* 读取第二张图片 宽高 */ int widthTwo = imageSecond.getWidth();// 图片宽度 int heightTwo = imageSecond.getHeight();// 图片高度 /* 计算总宽度 */ int w = 0; if (x + widthTwo > width) { w = widthTwo + x; } else { w = width; } /* 计算总高度 */ int h = 0; if (y + heightTwo > height) { h = heightTwo + y; } else { h = height; } /* 新建一个空白画布 */ image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics(); /* 设置背景透明 */ //image = g2d.getDeviceConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT); g2d = image.createGraphics(); g2d.drawImage(imageFirst, 0, 0, w, h, null); g2d.drawImage(imageSecond, x, y, widthTwo, heightTwo, null); return image; } catch (Exception e) { if (image != null) { image.flush(); } e.printStackTrace(); } return null; } /** * 生成商品分享海报 * @param headImg 头像 * @param productImg 商品图片 * @param qrFile 小程序码 * @param nickName * @param bgPath * @param goodsName * @param price * @throws Exception */ public static BufferedImage generateSharePoster(String headImg, String productImg, File qrFile, String nickName, String bgPath, String goodsName, String price) throws Exception{ // 提示语 String tips = "为您挑选了一个好物"; // 羊角符号 String pricePre = "¥"; // 背景图 BufferedImage bgBuffer = ImageIO.read(new URL(bgPath)); // 头像 BufferedImage avatarBuffer = ImageIO.read(new URL(headImg)); BufferedImage avatarMinRoundBuffer = roundImage(resizeByHeight(avatarBuffer, 120), 120, 120); // 头像合并 BufferedImage imgWithHeadImg = synthesisPicAtXy(bgBuffer, avatarMinRoundBuffer, 35, 65); Color black = new Color(0, 0, 0); // 黑色 Color grey = new Color(155, 155, 155); // 灰色 Color red = new Color(255, 0, 0); // 红色 // 添加用户昵称 BufferedImage imgWithName = addTxtAtXy(imgWithHeadImg, nickName, 180, 110, new Font("宋体", Font.PLAIN, 35), black); // 添加提示语 BufferedImage imgWithTips = addTxtAtXy(imgWithName, tips, 180, 160, new Font("宋体", Font.PLAIN, 35), grey); // 产品 BufferedImage productBuffer = ImageIO.read(new URL(productImg)); // 产品图片缩放 BufferedImage goodsMinBuffer = resizeByWidth(productBuffer, 678, 678); // 合成产品图片 BufferedImage imgWithGoods = synthesisPicAtXy(imgWithTips, goodsMinBuffer, 35, 205); // 合成羊角符 BufferedImage imgWithPricePre = addTxtAtXy(imgWithGoods, pricePre, 65, 955, new Font("宋体", Font.PLAIN, 40), red); // 合成价格 BufferedImage imgWithPrice = addTxtAtXy(imgWithPricePre, price, 95, 955, new Font("宋体", Font.PLAIN, 50), red); // 合成店铺名称 BufferedImage imgWithStoreName = addTxtAtXy(imgWithPrice, goodsName, 65, 1100, new Font("宋体", Font.PLAIN, 35), black); // 小程序码 BufferedImage qrcodeBuffer = ImageIO.read(qrFile); // 小程序码缩放 BufferedImage qrcodeMinBuffer = resizeByWidth(qrcodeBuffer, 170); // 小程序码合成 BufferedImage imgWithQrcode = synthesisPicAtXy(imgWithStoreName, qrcodeMinBuffer, 520, 1000); return imgWithQrcode; } /** * 获取指定字体指定内容的宽度 * @param font 字体 * @param content 内容 * @return */ public static int getWordWidth(Font font, String content) { FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font); int width = 0; for (int i = 0; i < content.length(); i++) { width += metrics.charWidth(content.charAt(i)); } return width; } /** * 获取指定字体指定内容的宽度 * @param font 字体 * @param content 内容 * @return */ public static int getWordWidthBody(Font font, String content) { FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font); return metrics.stringWidth(content); } /** * 按比例裁剪图片 * @param image 待处理的图片流 * @param startX 开始x坐标 * @param startY 开始y坐标 * @param endX 结束x坐标 * @param endY 结束y坐标 * @return */ public static BufferedImage crop(BufferedImage image, int startX, int startY, int endX, int endY) { int width = image.getWidth(); int height = image.getHeight(); if (startX <= -1) { startX = 0; } if (startY <= -1) { startY = 0; } if (endX <= -1) { endX = width - 1; } if (endY <= -1) { endY = height - 1; } BufferedImage result = new BufferedImage(endX, endY, image.getType()); for (int y = startY; y < endY + startY; y++) { for (int x = startX; x < endX + startX; x++) { int rgb = image.getRGB(x, y); result.setRGB(x - startX, y - startY, rgb); } } return result; } /** * 图片缩放 * @param originalImage 原始图片 * @param width 宽度 * @param height 高度 * @return */ public static BufferedImage zoomInImage(BufferedImage originalImage, int width, int height) { /* 新建一个空白画布 */ BufferedImage image = new BufferedImage(width, height, originalImage.getType()); Graphics2D g2d = image.createGraphics(); /* 设置背景透明 */ image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT); g2d = image.createGraphics(); g2d.drawImage(originalImage, 0, 0, width, height, null); g2d.dispose(); return image; } /** * 实现图像的等比缩放(固定宽度) * @param source 待处理的图片流 * @param targetW 宽度 * @return */ public static BufferedImage resizeByWidth(BufferedImage source, double targetW) { double targetH = 0; double width = source.getWidth();// 图片宽度 double height = source.getHeight();// 图片高度 targetH = targetW / width * height; return zoomInImage(source, (int) targetW, (int) targetH); } /** * 实现图像的等比缩放(固定宽度) * @param source 待处理的图片流 * @param targetW 宽度 * @return */ public static BufferedImage resizeByWidth(BufferedImage source, double targetW, double targetH) { return zoomInImage(source, (int) targetW, (int) targetH); } /** * 实现图像的等比缩放(固定高度) * @param source 待处理的图片流 * @param targetH 高度 * @return */ public static BufferedImage resizeByHeight(BufferedImage source, double targetH) { double targetW; double width = source.getWidth();// 图片宽度 double height = source.getHeight();// 图片高度 targetW = targetH / height * width; return zoomInImage(source, (int) targetW, (int) targetH); } /*** * 将图片处理为圆角图片 * @param srcImgPath 源图片文件路径 * @param destImgPath 新生成的图片的保存路径,需要带有保存的文件名和后缀 * @param targetSize 文件的边长,单位:像素,最终得到的是一张正方形的图,所以要求targetSize<=源文件的最小边长 * @param cornerRadius 圆角半径,单位:像素。如果=targetSize那么得到的是圆形图 * @return 文件的保存路径 * @throws IOException */ public static String roundImage(String srcImgPath, String destImgPath, int targetSize, int cornerRadius) { BufferedImage bufferedImage = null; BufferedImage circularBufferImage = null; try { bufferedImage = ImageIO.read(new File(srcImgPath)); circularBufferImage = roundImage(bufferedImage, targetSize, cornerRadius); ImageIO.write(circularBufferImage, "png", new File(destImgPath)); return destImgPath; } catch (Exception e) { e.printStackTrace(); } finally { if (bufferedImage != null) { bufferedImage.flush(); } if (circularBufferImage != null) { circularBufferImage.flush(); } } return destImgPath; } /** * 将图片处理为圆角图片 * * @param image 待处理图片 * @param targetSize 直径 * @param cornerRadius 圆角半径,单位:像素。如果=targetSize那么得到的是圆形图 * @return */ public static BufferedImage roundImage(BufferedImage image, int targetSize, int cornerRadius) { BufferedImage outputImage = new BufferedImage(targetSize, targetSize, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = outputImage.createGraphics(); g2d.setComposite(AlphaComposite.Src); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setColor(Color.WHITE); g2d.fill(new RoundRectangle2D.Float(0, 0, targetSize, targetSize, cornerRadius, cornerRadius)); g2d.setComposite(AlphaComposite.SrcAtop); g2d.drawImage(image, 0, 0, null); g2d.dispose(); return outputImage; } /** * 将第二张图片放到第一张的指定位置 * @param imageFirst * @param imageSecond * @param x * @param y */ public static BufferedImage synthesisPicAtXy(BufferedImage imageFirst, BufferedImage imageSecond, int x, int y) { BufferedImage image = null; try { /* 读取第一张图片 宽高 */ int width = imageFirst.getWidth();// 图片宽度 int height = imageFirst.getHeight();// 图片高度 /* 读取第二张图片 宽高 */ int widthTwo = imageSecond.getWidth();// 图片宽度 int heightTwo = imageSecond.getHeight();// 图片高度 /* 计算总宽度 */ int w = 0; if (x + widthTwo > width) { w = widthTwo + x; } else { w = width; } /* 计算总高度 */ int h = 0; if (y + heightTwo > height) { h = heightTwo + y; } else { h = height; } /* 新建一个空白画布 */ image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics(); /* 设置背景透明 */ image = g2d.getDeviceConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT); g2d = image.createGraphics(); g2d.drawImage(imageFirst, 0, 0, w, h, null); g2d.drawImage(imageSecond, x, y, widthTwo, heightTwo, null); return image; } catch (Exception e) { if (image != null) { image.flush(); } e.printStackTrace(); } return null; } /** * 将第二张图片放到第一张的指定位置 * @param first * @param second * @param out * @param x * @param y */ public static String synthesisPicAtXy(String first, String second, String out, int x, int y) { BufferedImage imageFirst = null; BufferedImage imageSecond = null; BufferedImage outBuffered = null; try { File fileOne = new File(first); imageFirst = ImageIO.read(fileOne); File fileTwo = new File(second); imageSecond = ImageIO.read(fileTwo); outBuffered = synthesisPicAtXy(imageFirst, imageSecond, x, y); File outFile = new File(out); assert outBuffered != null; ImageIO.write(outBuffered, "png", outFile);// 写图片 return out; } catch (Exception e) { e.printStackTrace(); } finally { if (imageFirst != null) { imageFirst.flush(); } if (imageSecond != null) { imageSecond.flush(); } if (outBuffered != null) { outBuffered.flush(); } } return null; } /** * 将文字添加到图片指定的位置 * @param src * @param out * @param x * @param y * @param center 可选居中 默认false * @return */ public static String addTxtAtXy(String src, String out, String txt, int x, int y, boolean center, Font font, Color color) { BufferedImage picBuffer = null; BufferedImage outBuffered; try { File fileOne = new File(src); picBuffer = ImageIO.read(fileOne); outBuffered = addTxtAtXy(picBuffer, txt, x, y, font, color); File outFile = new File(out); assert outBuffered != null; ImageIO.write(outBuffered, "png", outFile);// 写图片 return out; } catch (Exception e) { e.printStackTrace(); } finally { if (picBuffer != null) { picBuffer.flush(); } } return null; } /** * 将文字txt添加到图片指定的位置(x,y) * @param src * @param txt * @param x * @param y * @return */ public static BufferedImage addTxtAtXy(BufferedImage src, String txt, int x, int y, Font font, Color color) { BufferedImage outBuffer; try { /* 读取图片 宽高 */ int width = src.getWidth();// 图片宽度 int height = src.getHeight();// 图片高度 /* 新建一个空白画布 */ outBuffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = outBuffer.createGraphics(); /* 设置背景透明 */ outBuffer = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT); g2d = outBuffer.createGraphics(); g2d.drawImage(src, 0, 0, width, height, null); g2d.setColor(color); g2d.setFont(font); FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font); int widths = 0; // 520-65 = 455 String str = ""; int a = 0; for (int i = 0; i < txt.length(); i++) { str += txt.charAt(i); widths += metrics.charWidth(txt.charAt(i)); if(widths > 400) { if(a < 1) { y -= 25; g2d.drawString(str, x, y); str = ""; widths = 0; a++; y += 45; } } else if(widths > 380 && a >= 1) { str += "..."; g2d.drawString(str, x, y); a++; break; } } // 10,20 表示这段文字在图片上的位置(x,y) .第一个是你设置的内容。 if(a < 2) { g2d.drawString(str, x, y); } g2d.dispose(); return outBuffer; } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } return null; } /** * 将文字txt添加到图片指定y,x居中 * @param src * @param txt * @param y * @return */ public static BufferedImage addTxtAtXy(BufferedImage src, String txt, int y, Font font, Color color) { BufferedImage outBuffer; try { /* 读取图片 宽高 */ int width = src.getWidth();// 图片宽度 int height = src.getHeight();// 图片高度 /* 新建一个空白画布 */ outBuffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = outBuffer.createGraphics(); /* 设置背景透明 */ outBuffer = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT); g2d = outBuffer.createGraphics(); g2d.drawImage(src, 0, 0, width, height, null); g2d.setColor(color); g2d.setFont(font); FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font); int widths = 0; int body = getWordWidthBody(font, txt); int a1 = width / 2; int b1 = body / 2; int x = a1 - b1; // 520-65 = 455 String str = ""; int a = 0; for (int i = 0; i < txt.length(); i++) { str += txt.charAt(i); widths += metrics.charWidth(txt.charAt(i)); if(widths > 400) { if(a < 1) { y -= 25; g2d.drawString(str, x, y); str = ""; widths = 0; a++; y += 45; } } else if(widths > 380 && a >= 1) { str += "..."; g2d.drawString(str, x, y); a++; break; } } // 10,20 表示这段文字在图片上的位置(x,y) .第一个是你设置的内容。 if(a < 2) { g2d.drawString(str, x, y); } g2d.dispose(); return outBuffer; } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } return null; } }