java生成海報(bào)

DrawingUtils類(lèi)

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? ? 生成微信小程序的海報(bào)分享 , 并封裝一個(gè)隊(duì)圖片操作的代碼

* @auther 葉子

* @create 2019-12-21 17:01

*/

public class DrawingUtils {

private Fontfont =new Font("宋體", Font.BOLD,25);// 添加字體的屬性設(shè)置

? ? private Graphics2Dg =null;

private Graphics2DJ =null;

private int fontsize =0;

private int x =600;

private int y =1200;

/**

* 導(dǎo)入本地圖片到緩沖區(qū)

*/

? ? public BufferedImage loadImageLocal(String imgName) {

try {

return ImageIO.read(new File(imgName));

}catch (IOException e) {

System.out.println(e.getMessage());

}

return null;

}

/**

* 導(dǎo)入網(wǎng)絡(luò)圖片到緩沖區(qū)

*/

? ? 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());

}

}

}

/**

* 設(shè)定文字的字體等

*/

? ? public void setFont(String fontStyle,int fontSize) {

this.fontsize = fontSize;

this.font =new Font(fontStyle, Font.PLAIN, fontSize);

}

/**

* 修改圖片,返回修改后的圖片緩沖區(qū)(只輸出一行文本)

*/

? ? 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);// 設(shè)置字體顏色

? ? ? ? ? ? if (font !=null)

g.setFont(font);

// 驗(yàn)證輸出位置的縱坐標(biāo)和橫坐標(biāo)

? ? ? ? ? ? if (content !=null) {

g.drawString(content, x, y);

}

g.dispose();

}catch (Exception e) {

System.out.println(e.getMessage());

}

return img;

}

/**

* 修改圖片,返回修改后的圖片緩沖區(qū)(輸出多個(gè)文本段) xory:true表示將內(nèi)容在一行中輸出;false表示將內(nèi)容多行輸出

*/

? ? 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);

// 驗(yàn)證輸出位置的縱坐標(biāo)和橫坐標(biāo)

? ? ? ? ? ? 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;// 重新計(jì)算文本輸出位置

? ? ? ? ? ? ? ? ? ? }

}else {

for (int i =0; i < arrlen; i++) {

g.drawString(contentArr[i].toString(),this.x,this.y);

this.y +=this.fontsize +2+33;// 重新計(jì)算文本輸出位置

? ? ? ? ? ? ? ? ? ? }

}

}

g.dispose();

}catch (Exception e) {

System.out.println(e.getMessage());

}

return img;

}

/**

* 修改圖片,返回修改后的圖片緩沖區(qū)(只輸出一行文本)

*

* 時(shí)間: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);// 設(shè)置字體顏色

? ? ? ? ? ? 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個(gè)集群機(jī)器部署

? ? ? ? int hashCodeV = UUID.randomUUID().toString().hashCode();

if (hashCodeV <0) {// 有可能是負(fù)數(shù)

? ? ? ? ? ? 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;// 如果剪切出來(lái)的圖片畫(huà)質(zhì)模糊,請(qǐng)將width 調(diào)大點(diǎn).

// 透明底的圖片

? ? ? ? BufferedImage formatAvatarImage =new BufferedImage(width, width, BufferedImage.TYPE_4BYTE_ABGR);

Graphics2D graphics = formatAvatarImage.createGraphics();

// 把圖片切成一個(gè)圓

? ? ? ? graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

// 留一個(gè)像素的空白區(qū)域,這個(gè)很重要,畫(huà)圓的時(shí)候把這個(gè)覆蓋

? ? ? ? int border =1;

// 圖片是一個(gè)圓型

? ? ? ? Ellipse2D.Double shape =new Ellipse2D.Double(border, border, width - border *2, width - border *2);

// 需要保留的區(qū)域

? ? ? ? graphics.setClip(shape);

graphics.drawImage(avatarImage, border, border, width - border *2, width - border *2,null);

graphics.dispose();

// 在圓圖外面再畫(huà)一個(gè)圓

// 新創(chuàng)建一個(gè)graphics,這樣畫(huà)的圓不會(huì)有鋸齒

? ? ? ? graphics = formatAvatarImage.createGraphics();

graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

int border1 =3;

// 畫(huà)筆是4.5個(gè)像素,BasicStroke的使用可以查看下面的參考文檔

// 使畫(huà)筆時(shí)基本會(huì)像外延伸一定像素,具體可以自己使用的時(shí)候測(cè)試

? ? ? ? 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);// 發(fā)布項(xiàng)目時(shí),如:Tomcat 他會(huì)在服務(wù)器

//本地tomcat webapps文件下創(chuàng)建此文件名

? ? ? ? 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();// 刪除文件

? ? ? ? }

}

/**

* 調(diào)整bufferedimage大小

? ? * @param source BufferedImage 原始image

? ? * @param targetW int? 目標(biāo)寬

? ? * @param targetH int? 目標(biāo)高

? ? * @param flag boolean 是否同比例調(diào)整

? ? * @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();

//設(shè)置背景圖片

? ? ? ? BufferedImage j = tt.loadImageLocal("本地圖片");? ? ? ? ? ?//E:\\Users\\02.jpg

//設(shè)置小程序二維碼? ,? 二維碼圖片為自動(dòng)生成

? ? ? ? BufferedImage k = tt.loadImageLocal("本地圖片");

//用戶頭像

? ? ? ? BufferedImage f = tt.loadImageLocal("本地圖片");

//設(shè)置商品的圖片

? ? ? ? BufferedImage c = tt.loadImageLocal("本地圖片");

//要顯示的文字

//Object [] obj = {"禰豆子" , "¥1000.00【包郵】"};

//設(shè)置文字的x,y軸

? ? ? ? tt.modifyImageYe(j);

//設(shè)置小程序圖片大小

? ? ? ? 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));

//此處可重復(fù)多次合成多張圖片

//完成后即可上傳對(duì)象存儲(chǔ)

//filedel("C:\\Users\\Waitforyou\\Desktop\\img\\c1.jpg");//完成后刪除本地文件

? ? ? ? System.out.println("success");

}

}

DrawingRound類(lèi)

生成頭像圓角頭像

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 {

/**

* 圖片設(shè)置圓角

? ? * @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;

}

/**

* 圖片設(shè)置圓角

? ? * @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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容