生成画布代码:
class GenImageClassHB implements Runnable {
private String log;
private String like;
private String message;
private String message1;
private String message2;
private String text;
private String name;
private String file;
private String path;
//private Docservic docservic;
GenImageClassHB(String log,String like,String message,String message1,String message2,String text,
String name,String file,String path){
this.file=file;
this.like=like;
this.log=log;
this.name=name;
this.message=message;
this.message1=message1;
this.message2=message2;
this.text=text;
this.path=path;
}
@Override
public void run() {
try {
int width = 512, height = 908;
//int width = 430, height = 500;
// TYPE_INT_ARGB specifies the image format: 8-bit RGBA packed
// into integer pixels
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D ig2 = bi.createGraphics();
//创建整个画布
ig2.setComposite(AlphaComposite.Clear);
ig2.fillRoundRect(0, 0, width, height,80,80);
ig2.setComposite(AlphaComposite.Src);
ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
ig2.setColor(Color.blue);
//添加log
URL qrcodeImgurlLog = new URL(log);
BufferedImage qrcodeImgLog = ImageIO.read(qrcodeImgurlLog);
ig2.setComposite(AlphaComposite.SrcOut);
ig2.drawImage(qrcodeImgLog, 40, 10, 160, 44, null);
//读取客户喜欢的图片
URL userLikeurl = new URL(like);
BufferedImage qrcodeImgLike = ImageIO.read(userLikeurl);
int likeW =qrcodeImgLike.getWidth();
int likeH =qrcodeImgLike.getHeight();
// //使其变圆
qrcodeImgLike = roundImage(qrcodeImgLike, likeW, likeH, 60);
double dlikeW =(double)likeW;
double dlikeH =(double)likeH;
//比较图片的高和宽
if(dlikeW>dlikeH){
double hw =(dlikeH)/(dlikeW);
if(hw>=0.75){
likeH =314;
double w =314/hw;
likeW =new Double(w).intValue();
}else {
likeW =416;
likeH =new Double(416*hw).intValue();
}
}else {
double wh=dlikeH/dlikeW;
likeH=314;
likeW=new Double(314/wh).intValue();
}
//把客户喜欢的图片放入画布
int likeX=new Double((512 -likeW)/2).intValue();
int likeY=new Double((314-likeH)/2).intValue()+64;
ig2.setComposite(AlphaComposite.Src);
ig2.drawImage(qrcodeImgLike, likeX, likeY, likeW, likeH, null);
//设置字体
Font font = new Font(".萍方-简", Font.BOLD, 22);
float fontSize = getMaxFittingFontSize(message, 320, 45, ig2, font);
font = font.deriveFont(fontSize);
ig2.setFont(font);
//设置字体位置
FontMetrics fontMetrics = ig2.getFontMetrics();
int stringWidth = fontMetrics.stringWidth(message);
int stringHeight = fontMetrics.getAscent();
ig2.setPaint(Color.black);
System.out.println("字体:" + font.getName() + "风格:" + font.getStyle() + "大小:" + font.getSize()
+ "font.getFamily():" + font.getFamily() + "font.getFontName():" + font.getFontName());
//ig2.drawString(message, (600 - stringWidth) / 2, 520 - (70 - stringHeight) / 2);
ig2.drawString(message, (512 - stringWidth) / 2, 424-(45-stringHeight)/2);
//设置字体1
Font font1 = new Font(".萍方-简", Font.BOLD, 19);
float fontSize1 = getMaxFittingFontSize(message1, 320, 43, ig2, font1);
font1 = font1.deriveFont(fontSize1);
ig2.setFont(font1);
//设置字体位置
FontMetrics fontMetrics1 = ig2.getFontMetrics();
int stringWidth1 = fontMetrics1.stringWidth(message1);
int stringHeight1 = fontMetrics1.getAscent();
ig2.setPaint(Color.black);
//ig2.drawString(message, (600 - stringWidth) / 2, 520 - (70 - stringHeight) / 2);
ig2.drawString(message1, (512 - stringWidth1) / 2, 469-(43-stringHeight1)/2);
//设置字体2
Font font2 = new Font(".萍方-简", Font.PLAIN, 10);
float fontSize2 = getMaxFittingFontSize(message2, 430, 40, ig2, font2);
font2 = font2.deriveFont(fontSize2);
ig2.setFont(font2);
//设置字体位置2
FontMetrics fontMetrics2 = ig2.getFontMetrics();
int stringWidth2 = fontMetrics2.stringWidth(message2);
int stringHeight2 = fontMetrics2.getAscent();
ig2.setPaint(Color.black);
//ig2.drawString(message, (600 - stringWidth) / 2, 520 - (70 - stringHeight) / 2);
ig2.drawString(message2, (512 - stringWidth2) / 2, 513-(40-stringHeight2)/2);
//生成二维码图片
//不含Logo
// QrCodeUtils.encode(text, null, "C:\\ptzy\\tp", "qrcodeImg", true);
QrCodeUtils.encode(text, null, path, name, true);
//读取二维码图片
//URL qrcodeImgurl1 = new URL("file:\\C:\\ptzy\\tp\\.jpg");
URL qrcodeImgurl = new URL("file:\\"+path+"\\"+name+".jpg");
BufferedImage qrcodeImg1 = ImageIO.read(qrcodeImgurl);
//把二维码的图片写入画布
ig2.setComposite(AlphaComposite.SrcOut);
ig2.drawImage(qrcodeImg1, 64, 520, 384, 384, null);
File newFile = new File(file);
newFile.mkdirs();
ImageIO.write(bi, "PNG", newFile);
} catch (Exception e) {
e.printStackTrace();
}
}
public static float getMaxFittingFontSize(String string, int width, int height, Graphics g, Font font) {
int minSize = 0;
int maxSize = 72;
int curSize = font.getSize();
while (maxSize - minSize > 2) {
FontMetrics fm = g.getFontMetrics(new Font(font.getName(), font.getStyle(), curSize));
int fontWidth = fm.stringWidth(string);
int fontHeight = fm.getLeading() + fm.getMaxAscent() + fm.getMaxDescent();
if ((fontWidth > width) || (fontHeight > height)) {
maxSize = curSize;
curSize = (maxSize + minSize) / 2;
} else {
minSize = curSize;
curSize = (minSize + maxSize) / 2;
}
}
return curSize;
}
static BufferedImage roundImage(BufferedImage image, int targetSize, int targetSize1, int cornerRadius) {
BufferedImage outputImage = new BufferedImage(targetSize, targetSize1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = outputImage.createGraphics();
g2.setComposite(AlphaComposite.Src);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.WHITE);
g2.fill(new RoundRectangle2D.Float(0, 0, targetSize, targetSize1, cornerRadius, cornerRadius));
g2.setComposite(AlphaComposite.SrcAtop);
g2.drawImage(image, 0, 0,targetSize,targetSize1, null);
g2.dispose();
return outputImage;
}
public static double GetWidthOfAttributedString(Graphics2D graphics2D, AttributedString attributedString) {
AttributedCharacterIterator characterIterator = attributedString.getIterator();
FontRenderContext fontRenderContext = graphics2D.getFontRenderContext();
LineBreakMeasurer lbm = new LineBreakMeasurer(characterIterator, fontRenderContext);
TextLayout textLayout = lbm.nextLayout(Integer.MAX_VALUE);
return textLayout.getBounds().getWidth();
}
public static void main(String[] args) {
String log="file:\\C:\\ptzy\\tp\\log.jpg";
String like="file:\\C:\\ptzy\\tp\\userlike.jpg";
String message="张三(大师兄)";
String message1="赛马资本(0000001)合伙人";
String message2="既然选择了远方,便注定风雨兼程!";
String text="https://blog.csdn.net/Povemetin?spm=1001.2014.3001.5113";
String name="qrcodeImg";
String path="C:\\ptzy\\tp";
String file="C:\\ptzy\\tp\\1.jpg";
GenImageClassHB genImageClassHB = new GenImageClassHB(log,like,message,message1, message2, text,
name, file,path);
Thread thread=new Thread(genImageClassHB);
thread.start();
thread.run();
}
}
生成二维码图片代码
public class QrCodeUtils {
private static final String CHARSET = "utf-8";
private static final String FORMAT = "JPG";
// 二维码尺寸
private static final int QRCODE_SIZE = 300;
// LOGO宽度
private static final int LOGO_WIDTH = 60;
// LOGO高度
private static final int LOGO_HEIGHT = 60;
private static BufferedImage createImage(String content, String logoPath, boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
if (logoPath == null || "".equals(logoPath)) {
return image;
}
// 插入图片
QrCodeUtils.insertImage(image, logoPath, needCompress);
return image;
}
private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception {
File file = new File(logoPath);
if (!file.exists()) {
throw new Exception("logo file not found.");
}
Image src = ImageIO.read(new File(logoPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > LOGO_WIDTH) {
width = LOGO_WIDTH;
}
if (height > LOGO_HEIGHT) {
height = LOGO_HEIGHT;
}
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
public static String encode(String content, String logoPath, String destPath, boolean needCompress) throws Exception {
BufferedImage image = QrCodeUtils.createImage(content, logoPath, needCompress);
mkdirs(destPath);
String fileName = new Random().nextInt(99999999) + "." + FORMAT.toLowerCase();
ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));
return fileName;
}
public static String encode(String content, String logoPath, String destPath, String fileName, boolean needCompress) throws Exception {
BufferedImage image = QrCodeUtils.createImage(content, logoPath, needCompress);
mkdirs(destPath);
fileName = fileName.substring(0, fileName.indexOf(".")>0?fileName.indexOf("."):fileName.length())
+ "." + FORMAT.toLowerCase();
ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));
return fileName;
}
public static void mkdirs(String destPath) {
File file = new File(destPath);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
public static String encode(String content, String logoPath, String destPath) throws Exception {
return QrCodeUtils.encode(content, logoPath, destPath, false);
}
public static String encode(String content, String destPath, boolean needCompress) throws Exception {
return QrCodeUtils.encode(content, null, destPath, needCompress);
}
public static String encode(String content, String destPath) throws Exception {
return QrCodeUtils.encode(content, null, destPath, false);
}
public static void encode(String content, String logoPath, OutputStream output, boolean needCompress)
throws Exception {
BufferedImage image = QrCodeUtils.createImage(content, logoPath, needCompress);
ImageIO.write(image, FORMAT, output);
}
public static void encode(String content, OutputStream output) throws Exception {
QrCodeUtils.encode(content, null, output, false);
}
public static String decode(File file) throws Exception {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
public static String decode(String path) throws Exception {
return QrCodeUtils.decode(new File(path));
}
public static void main(String[] args) throws Exception {
String text = "https://blog.csdn.net/ianly123";
//不含Logo
//QrCodeUtils2.encode(text, null, "/Users/ianly/Documents/picture", true);
//含Logo,不指定二维码图片名
//QrCodeUtils2.encode(text, "/Users/ianly/Documents/picture/google-icon.jpg", "/Users/ianly/Documents/picture/", true);
//含Logo,指定二维码图片名
QrCodeUtils.encode(text, "/Users/ianly/Documents/picture/google-icon.jpg", "/Users/ianly/Documents/picture", "qrcode", true);
}
}
附上图