DrawingUtils类
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;
/**
* @Description 生成微信小程序的海报分享 , 并封装一个队图片操作的代码
* @auther 叶子
* @create 2019-12-21 17:01
*/
public class DrawingUtils {
private Fontfont =new Font("宋体", Font.BOLD,25);// 添加字体的属性设置
private Graphics2Dg =null;
private Graphics2DJ =null;
private int fontsize =0;
private int x =600;
private int y =1200;
/**
* 导入本地图片到缓冲区
*/
public BufferedImage loadImageLocal(String imgName) {
try {
return ImageIO.read(new File(imgName));
}catch (IOException e) {
System.out.println(e.getMessage());
}
return null;
}
/**
* 导入网络图片到缓冲区
*/
public BufferedImage loadImageUrl(String imgName) {
try {
URL url =new URL(imgName);
return ImageIO.read(url);
}catch (IOException e) {
System.out.println(e.getMessage());
}
return null;
}
/**
* 生成新图片到本地
*/
public void writeImageLocal(String newImage, BufferedImage img) {
if (newImage !=null && img !=null) {
try {
File outputfile =new File(newImage);
ImageIO.write(img,"jpg", outputfile);
}catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
/**
* 设定文字的字体等
*/
public void setFont(String fontStyle,int fontSize) {
this.fontsize = fontSize;
this.font =new Font(fontStyle, Font.PLAIN, fontSize);
}
/**
* 修改图片,返回修改后的图片缓冲区(只输出一行文本)
*/
public BufferedImage modifyImage(BufferedImage img, String content,int x,int y, Font font, Color color) {
try {
g = img.createGraphics();
g.setBackground(Color.WHITE);
g.setColor(color);// 设置字体颜色
if (font !=null)
g.setFont(font);
// 验证输出位置的纵坐标和横坐标
if (content !=null) {
g.drawString(content, x, y);
}
g.dispose();
}catch (Exception e) {
System.out.println(e.getMessage());
}
return img;
}
/**
* 修改图片,返回修改后的图片缓冲区(输出多个文本段) xory:true表示将内容在一行中输出;false表示将内容多行输出
*/
public BufferedImage modifyImage(BufferedImage img, Object[] contentArr,int x,int y,boolean xory) {
try {
int w = img.getWidth();
int h = img.getHeight();
g = img.createGraphics();
g.setBackground(Color.white);
g.setColor(Color.black);
if (this.font !=null)
g.setFont(this.font);
// 验证输出位置的纵坐标和横坐标
if (x >= h || y >= w) {
this.x = h -this.fontsize +2;
this.y = w;
}else {
this.x = x;
this.y = y;
}
if (contentArr !=null) {
int arrlen = contentArr.length;
if (xory) {
for (int i =0; i < arrlen; i++) {
g.drawString(contentArr[i].toString(),this.x,this.y);
this.x += contentArr[i].toString().length() *this.fontsize /2 +33;// 重新计算文本输出位置
}
}else {
for (int i =0; i < arrlen; i++) {
g.drawString(contentArr[i].toString(),this.x,this.y);
this.y +=this.fontsize +2+33;// 重新计算文本输出位置
}
}
}
g.dispose();
}catch (Exception e) {
System.out.println(e.getMessage());
}
return img;
}
/**
* 修改图片,返回修改后的图片缓冲区(只输出一行文本)
*
* 时间:2019-12-23
*
* @param img
* @return
*/
public BufferedImage modifyImageYe(BufferedImage img) {
try {
int w = img.getWidth();
int h = img.getHeight();
g = img.createGraphics();
g.setBackground(Color.WHITE);
g.setColor(Color.RED);// 设置字体颜色
if (this.font !=null)
g.setFont(new Font("宋体",Font.BOLD,35));
g.drawString("祢豆子",50,550);
g.setFont(new Font("宋体",Font.BOLD,25));
g.drawString("¥1000",50,580);
g.setFont(new Font("宋体",Font.BOLD,25));
g.drawString("如果我是DJ",180,840);
g.drawString("分享商品可获取商品返利",50 ,900);
g.dispose();
}catch (Exception e) {
System.out.println(e.getMessage());
}
return img;
}
/**
* 合成图片
* @param b 图片 1
* @param d 图片 2
* @param X
* @param Y
* @return
*/
public BufferedImage modifyImagetogeter(BufferedImage b, BufferedImage d, BufferedImage f , BufferedImage commodit ,int X,int Y) {
try {
int w = b.getWidth();
int h = b.getHeight();
g = d.createGraphics();
g.drawImage(b, X, Y, w, h,null);
g.drawImage(f ,50 ,770 ,100 ,100 ,null);
g.drawImage(commodit ,0 ,0 ,514 ,500 ,null);
g.dispose();
}catch (Exception e) {
System.out.println(e.getMessage());
}
return d;
}
/**
* 从url中读取图片
*
* @param urlHttp
* @param path
*/
public static String getPicture(String urlHttp, String path) {
int machineId =1;// 最大支持1-9个集群机器部署
int hashCodeV = UUID.randomUUID().toString().hashCode();
if (hashCodeV <0) {// 有可能是负数
hashCodeV = -hashCodeV;
}
String file = path + machineId + String.format("%015d", hashCodeV) +".jpg";
try {
URL url =new URL(urlHttp);
BufferedImage img = ImageIO.read(url);
ImageIO.write(img,"jpg",new File(file));
}catch (Exception e) {
e.printStackTrace();
}
return file;
}
public static void pichead(String url, String path)throws MalformedURLException, IOException {
BufferedImage avatarImage = ImageIO.read(new URL(url));
int width =84;// 如果剪切出来的图片画质模糊,请将width 调大点.
// 透明底的图片
BufferedImage formatAvatarImage =new BufferedImage(width, width, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D graphics = formatAvatarImage.createGraphics();
// 把图片切成一个圓
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 留一个像素的空白区域,这个很重要,画圆的时候把这个覆盖
int border =1;
// 图片是一个圆型
Ellipse2D.Double shape =new Ellipse2D.Double(border, border, width - border *2, width - border *2);
// 需要保留的区域
graphics.setClip(shape);
graphics.drawImage(avatarImage, border, border, width - border *2, width - border *2,null);
graphics.dispose();
// 在圆图外面再画一个圆
// 新创建一个graphics,这样画的圆不会有锯齿
graphics = formatAvatarImage.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int border1 =3;
// 画笔是4.5个像素,BasicStroke的使用可以查看下面的参考文档
// 使画笔时基本会像外延伸一定像素,具体可以自己使用的时候测试
Stroke s =new BasicStroke(4.5F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
graphics.setStroke(s);
graphics.setColor(Color.WHITE);
graphics.drawOval(border1, border1, width - border1 *2, width - border1 *2);
graphics.dispose();
OutputStream os =new FileOutputStream(path);// 发布项目时,如:Tomcat 他会在服务器
//本地tomcat webapps文件下创建此文件名
ImageIO.write(formatAvatarImage,"PNG", os);
os.close();
}
/**
* 删除文件
*
* @param filedel
*/
public static void filedel(String filedel) {
File file =new File(filedel);
if (!file.exists()) {
System.out.println("文件不存在");
}else {
System.out.println("存在文件");
file.delete();// 删除文件
}
}
/**
* 调整bufferedimage大小
* @param source BufferedImage 原始image
* @param targetW int 目标宽
* @param targetH int 目标高
* @param flag boolean 是否同比例调整
* @return BufferedImage 返回新image
*/
private static BufferedImage resizeBufferedImage(BufferedImage source,int targetW,int targetH,boolean flag ,int state) {
int type = source.getType();
BufferedImage target =null;
double xex =0.5;
double xey =4;
double sx=0;
double sy =0;
if(state ==1){
sx = (double) targetW / source.getWidth() - xex;
sy = (double) targetH / source.getHeight() - xey;
}else {
sx = (double) targetW / source.getWidth() - xex;
sy = (double) targetH / source.getHeight() -0.0;
System.out.println("sy "+sy);
}
if (flag && sx > sy) {
sx = sy;
targetW = (int) (sx * source.getWidth());
}else if(flag && sx <= sy){
sy = sx;
targetH = (int) (sy * source.getHeight());
}
if (type == BufferedImage.TYPE_CUSTOM) {// handmade
ColorModel cm = source.getColorModel();
WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);
boolean alphaPremultiplied = cm.isAlphaPremultiplied();
target =new BufferedImage(cm, raster, alphaPremultiplied,null);
}else {
target =new BufferedImage(targetW, targetH, type);
}
Graphics2D g = target.createGraphics();
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
g.dispose();
return target;
}
public static void main(String[] args)throws MalformedURLException, IOException {
DrawingUtils tt =new DrawingUtils();
//设置背景图片
BufferedImage j = tt.loadImageLocal("本地图片"); //E:\\Users\\02.jpg
//设置小程序二维码 , 二维码图片为自动生成
BufferedImage k = tt.loadImageLocal("本地图片");
//用户头像
BufferedImage f = tt.loadImageLocal("本地图片");
//设置商品的图片
BufferedImage c = tt.loadImageLocal("本地图片");
//要显示的文字
//Object [] obj = {"祢豆子" , "¥1000.00【包邮】"};
//设置文字的x,y轴
tt.modifyImageYe(j);
//设置小程序图片大小
BufferedImage bufferedImage =resizeBufferedImage(k,300 ,1200 ,true ,1);
//修改背景图
//BufferedImage bj = resizeBufferedImage(c,514 ,800 ,true , 0);
//生成合成图片
tt.writeImageLocal("8.png", tt.modifyImagetogeter(bufferedImage, j, DrawingRound.setRadius(f) , c,350,780));
//此处可重复多次合成多张图片
//完成后即可上传对象存储
//filedel("C:\\Users\\Waitforyou\\Desktop\\img\\c1.jpg");//完成后删除本地文件
System.out.println("success");
}
}
DrawingRound类
生成头像圆角头像
package com.example.diandao.weixin.share;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
/**
* @Description
* @auther 叶子
* @create 2019-12-23 18:16
*/
public class DrawingRound {
/**
* 图片设置圆角
* @param srcImage 图片地址
* @param radius
* @param border
* @param padding
* @return
* @throws IOException
*/
public static BufferedImage setRadius(BufferedImage srcImage,int radius,int border,int padding)throws IOException {
int width = srcImage.getWidth();
int height = srcImage.getHeight();
int canvasWidth = width + padding *2;
int canvasHeight = height + padding *2;
BufferedImage image =new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D gs = image.createGraphics();
gs.setComposite(AlphaComposite.Src);
gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gs.setColor(Color.WHITE);
gs.fill(new RoundRectangle2D.Float(0,0, canvasWidth, canvasHeight, radius, radius));
gs.setComposite(AlphaComposite.SrcAtop);
gs.drawImage(setClip(srcImage, radius), padding, padding,null);
if(border !=0){
gs.setColor(Color.GRAY);
gs.setStroke(new BasicStroke(border));
gs.drawRoundRect(padding, padding, canvasWidth -2 * padding, canvasHeight -2 * padding, radius, radius);
}
gs.dispose();
return image;
}
/**
* 图片设置圆角
* @param srcImage
* @return
* @throws IOException
*/
public static BufferedImage setRadius(BufferedImage srcImage)throws IOException{
int radius = (srcImage.getWidth() + srcImage.getHeight()) /1;
return setRadius(srcImage, radius,2,5);
}
/**
* 图片切圆角
* @param srcImage
* @param radius
* @return
*/
public static BufferedImage setClip(BufferedImage srcImage,int radius){
int width = srcImage.getWidth();
int height = srcImage.getHeight();
BufferedImage image =new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D gs = image.createGraphics();
gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gs.setClip(new RoundRectangle2D.Double(0,0, width, height, radius, radius));
gs.drawImage(srcImage,0,0,null);
gs.dispose();
return image;
}
}
原文地址:https://download.csdn.net/download/u011768325/7653157