最近自在做个项目,需要使用到水印图片,以及java文字描边,网上查找资料都七零八落,不太直观,也比较难找到自己想要的东西,下面就是自己整合成功的demo以及上传部分的代码
package com.osa.platform.constant;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageUtils {
public static void main(String[] args) throws IOException {
String inputImagePath = "/Users/eko/Documents/hb.png";
String outputPath = "/Users/eko/Documents/hb1.png";
String text = "0.60元红包";
System.err.println(text.length());
addTextToImage(inputImagePath, outputPath, text, new Color(231, 65, 51));
}
public static void addTextToImage(String inputImagePath,String outputPath,String text,Color color) throws IOException{
File file = new File(inputImagePath);
Image image = ImageIO.read(file);
BufferedImage bi = new BufferedImage(image.getWidth(null),image.getHeight(null),BufferedImage.TYPE_INT_ARGB);
System.err.println(bi.getWidth());
float alpha = 1F;
Graphics2D g2 = bi.createGraphics();
//高清代码
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
g2.setComposite(ac);
g2.drawImage(image, 0, 0, image.getWidth(null), image.getHeight(null), null);
g2.setColor(color);
g2.setBackground(Color.BLACK);
Font font = new Font("微软雅黑",Font.BOLD,18);
g2.setFont(font);
FontRenderContext frc = g2.getFontRenderContext();
TextLayout tl = new TextLayout(text, font, frc);
FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
int stringWidth = fm.stringWidth(text);
Shape sha = tl.getOutline(AffineTransform.getTranslateInstance((bi.getWidth()-stringWidth)/2,115));
//字体色
g2.setColor(Color.red);
g2.draw(sha);
//描边色
g2.setColor(Color.white);
g2.fill(sha);
ImageIO.write(bi, "PNG", new FileOutputStream(outputPath));
}
}
结果如下:
//2.水印的纯文字拼接,不带描边的实现
package com.osa.platform.constant;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageUtils {
public static void main(String[] args) throws IOException {
String inputImagePath = "/Users/eko/Documents/hb.png";
String outputPath = "/Users/eko/Documents/hb1.png";
String text = "88元红包";
System.err.println(text.length());
addTextToImage(inputImagePath, outputPath, text, new Color(231, 65, 51));
}
public static void addTextToImage(String inputImagePath,String outputPath,String text,Color color) throws IOException{
File file = new File(inputImagePath);
Image image = ImageIO.read(file);
BufferedImage bi = new BufferedImage(image.getWidth(null),image.getHeight(null),BufferedImage.TYPE_INT_ARGB);
float alpha = 1F;
Graphics2D g2 = bi.createGraphics();
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
g2.setComposite(ac);
g2.drawImage(image, 0, 0, image.getWidth(null), image.getHeight(null), null);
g2.setColor(color);
g2.setBackground(Color.BLACK);
Font font = new Font("微软雅黑",Font.BOLD,18);
g2.setFont(font);
FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
int stringWidth = fm.stringWidth(text);
g2.drawString(text, (image.getWidth(null)-stringWidth)/2, 115);
g2.dispose();
ImageIO.write(bi, "PNG", new FileOutputStream(outputPath));
}
}
效果如下:
上传图片部分代码:
package com.osa.platform.service;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.osa.global.utils.DoHttp;
import com.osa.platform.utils.BaseResponse;
import com.osa.platform.utils.ConfigUtils;
import com.osa.platform.utils.FtpUpload;
import com.osa.platform.utils.HTTPSentUtils;
import com.osa.platform.utils.OsaResult;
import com.osa.platform.utils.utils.Common;
/**
* 红包图片加上水印文字
* @author eko
*
*/
@Service
public class ImageService {
private static final Logger LOGGER=LoggerFactory.getLogger(ImageService.class);
/**
* 给图片添加“图片水印”、可设置图片水印旋转角度
* @param srcImgPath 源图片路径
*/
public String markImageByText(HttpServletResponse response,String sourceUrl,String prizeName) {
String srcUrl=ConfigUtils.getConfig("image.server");
OutputStream os = null;
ByteArrayOutputStream bos=null;
try {
//1、源图片
String url=srcUrl+sourceUrl;
byte[] imgByte = getImgByte(url);
if(imgByte==null){
return null;
}
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imgByte);
Image srcImg = ImageIO.read(byteArrayInputStream);
BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),srcImg.getHeight(null),BufferedImage.TYPE_INT_ARGB);
float alpha = 1F;
Graphics2D g2 = buffImg.createGraphics();
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
g2.setComposite(ac);
g2.drawImage(srcImg, 0, 0, srcImg.getWidth(null), srcImg.getHeight(null), null);
Color color= new Color(231, 65, 51);
g2.setColor(color);
g2.setBackground(Color.BLACK);
Font font = new Font("微软雅黑",Font.BOLD,18);
g2.setFont(font);
FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
int stringWidth = fm.stringWidth(prizeName);
g2.drawString(prizeName, (srcImg.getWidth(null)-stringWidth)/2, 115);
g2.dispose();
File directory = new File("");// 参数为空
String realPath = directory.getCanonicalPath();
String mbFilePath=realPath+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"static"+File.separator+"temp"+"hbSY.png";
//5、生成图片
os=new FileOutputStream(new File(mbFilePath));
ImageIO.write(buffImg,"png",os);
bos = new ByteArrayOutputStream();
ImageIO.write(buffImg,"png",bos);
final InputStream is = new ByteArrayInputStream(bos.toByteArray());
String filePath = Common.getFilePath();
filePath="/temp"+filePath;
BaseResponse osa;
try {
osa = FtpUpload.getUploadResult(is, false,"hbSY.png",filePath);
if(osa.getStatus()==200){
Map
String imgUrl = map.get("keyUrl");
return imgUrl;
}
} catch (IOException e) {
LOGGER.error("红包图片生成异常,{}",e);
}
} catch (Exception e) {
LOGGER.error("红包图片生成异常,{}",e);
} finally {
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(bos);
}
return null;
}
public byte[] getImgByte(String url){
if(StringUtils.isBlank(url)){
return null;
}
url=getUrl(url);
byte[] imgByte = HTTPSentUtils.doGet(url);
return imgByte;
}
private String getUrl(String url){
int last = url.lastIndexOf("/");
String pre = url.substring(0, last+1);
String name = url.substring(last+1);
try {
name = URLEncoder.encode(name,"UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("编码失败,{}",e);
}
url=pre+name;
return url;
}
}