java合成图片 博客分类: Java JavaSpringStrutsSUNServlet
程序员文章站
2024-03-07 09:58:26
...
Class1
Class2 createJpg
模板
合成后的图片
package com.company.erp.exam.gw_certificate.action; /*------------------------------------------------------------------------------------------------------------------*/ /* 版本ID 日期 姓名 改版内容 /*------------------------------------------------------------------------------------------------------------------*/ import java.awt.Color; import java.awt.Font; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import com.company.erp.common.gw_certificate.databean.Gw_certificateDO; import com.company.erp.common.gw_certificate.form.Gw_certificateForm; import com.company.erp.common.gw_certtemp.databean.Gw_certtempDO; import com.company.erp.common.purview_organization.databean.Purview_organizationDO; import com.company.erp.common.purview_user.databean.Purview_userDO; import com.company.erp.common.system_basicdata.databean.System_basicdataDO; import com.company.erp.exam.gw_certificate.databean.Gw_certificateViewDO; import com.company.erp.exam.gw_certificate.si.Gw_certificateSI; import com.company.erp.system.bo.System_urlBO; import com.company.util.Common; import com.company.util.ObjectEvaluate; import com.gsf.arch.BaseAction; import com.gsf.tool.calendar.DateUtil; import com.gsf.tool.constant.Custom; import com.gsf.tool.exception.BaseException; import com.gsf.tool.image.dto.LetterDTO; import com.gsf.tool.image.util.CreateImage; /** * * 查看 证书 */ public class Gw_certificateSI_retrieve_selectAction extends BaseAction { public void myLogic(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response,HashMap beanMap) throws BaseException { Gw_certificateForm curForm=(Gw_certificateForm)form; Gw_certificateDO curDO = (Gw_certificateDO)curForm.getDO(); //通过spring的配置文件来调用,这样的好处是利用了spring的事务管理 Gw_certificateSI si = new Gw_certificateSI(); curDO=(Gw_certificateDO)si._retrieve(curDO); //将BaseDO对象数组转换为ActionForm数组 String cacheName = "Certtemp"; String className = Gw_certtempDO.class.getName(); Long certtemp_id = curDO.getCerttemp_id(); Gw_certtempDO gw_certtempDO = null ; //user的id Long user_id = curDO.getUser_id(); //获取考证时间 作为 发证时间 ; Date examTime = curDO.getExamTime(); Date expiredDate = curDO.getExpiredDate(); Purview_userDO purview_userDO = null; //从cache中获得用户的信息 if(user_id != null){ purview_userDO = (Purview_userDO)Common.parseDBCache_Row("PURVIEW_USER", user_id.toString(),Purview_userDO.class.getName()); } Long certificatePictureAddrURL = null; String newJPGFileName = null ; if( certtemp_id != null ){ gw_certtempDO = (Gw_certtempDO)Common.parseDBCache_Row(cacheName, certtemp_id.toString(), className); } if( gw_certtempDO != null ){ certificatePictureAddrURL = gw_certtempDO.getCertificatePictureAddrURL(); String backImageFileName = ""; if(certificatePictureAddrURL != null) backImageFileName = System_urlBO.getPath(certificatePictureAddrURL); //还要增加用户的基本信息 ArrayList letterDTO_list = getLetters(gw_certtempDO,purview_userDO,examTime, expiredDate); ArrayList imageDTO_list= new ArrayList(); CreateImage createImage = new CreateImage(); String tempJPGFileName=Common.getFileMainNameByUserSession(request) + ".jpg"; newJPGFileName=tempJPGFileName; Date currentDBDate=Common.getDBCurrentDate_Memory(); String currentDBDate_str=DateUtil.format(currentDBDate,"yyyyMMdd"); String tempItemName="tempCertificate"; String physicalPath = Common.getParaCacheItemValue(tempItemName); physicalPath=Common.getFilePath(physicalPath,Custom.fileSeparator,currentDBDate_str); newJPGFileName=physicalPath+newJPGFileName; if(!new File(physicalPath).isDirectory()) { new File(physicalPath).mkdirs(); } if(!backImageFileName.equals("")) createImage.createJpg(backImageFileName, imageDTO_list, letterDTO_list,newJPGFileName); newJPGFileName=tempJPGFileName; String virtualPath = Common.getParaCacheItemWeburl(tempItemName); virtualPath=Common.getFilePath(virtualPath,"/",currentDBDate_str); newJPGFileName=virtualPath+newJPGFileName; } // 判断领取没 request.setAttribute("fileName" ,newJPGFileName); } public ArrayList getLetters( Gw_certtempDO gw_certtempDO , Purview_userDO purview_userDO ,Date examTime, Date expiredDate){ ArrayList letterDTO_list = new ArrayList(); Calendar calendar =Calendar.getInstance(); calendar.setTime(examTime); String year = calendar.get(Calendar.YEAR)+""; String month = calendar.get(Calendar.MONTH)+1+""; String day = calendar.get(Calendar.DAY_OF_MONTH)+""; Calendar calendar1 =Calendar.getInstance(); calendar1.setTime(expiredDate); String yeare = calendar1.get(Calendar.YEAR)+""; String monthe = calendar1.get(Calendar.MONTH)+1+""; String daye = calendar1.get(Calendar.DAY_OF_MONTH)+""; // 证书模板的名称 String certtempName = gw_certtempDO.getCerttempName(); String certtempNameXY = gw_certtempDO.getCerttempNameXY(); LetterDTO letterCerttempNameDTO = getLetter(certtempName,certtempNameXY,"黑体","40","#000000"); letterDTO_list.add(letterCerttempNameDTO); // 签发单位 String signname = gw_certtempDO.getCertificateSignname(); String signnameXY = gw_certtempDO.getCertificateSignnameXY(); LetterDTO letterSignNameDTO = getLetter(signname,signnameXY,"宋体","20","#000000"); letterDTO_list.add(letterSignNameDTO); // 姓名 String userName = null; String identityCard = null; Long specialtyCode = null; Long positionCode = null; Long gradeCode = null; Long userOrg_id = null ; String userOrgName = null ; String db_cacheSpecialityName = "Speciality"; String db_cachePostName = "Post"; String db_cacheGradeName = "Grade"; String db_cacheOrganizationName = "organization"; //专业岗位等级的名称 String certificateType = ""; if(purview_userDO!= null ){ userName = purview_userDO.getLastNameFirs(); identityCard = purview_userDO.getIdentityCard(); userOrg_id = purview_userDO.getOrganization_id(); //根据证书模板上的专业、岗位、等级 specialtyCode = gw_certtempDO.getSpecialtyCode(); positionCode = gw_certtempDO.getPositionCode(); gradeCode = gw_certtempDO.getGradeCode(); if( userOrg_id != null ){ Purview_organizationDO purview_organizationDO = (Purview_organizationDO)Common.parseDBCache_Row(db_cacheOrganizationName, userOrg_id.toString(),Purview_organizationDO.class.getName()); if( purview_organizationDO != null ){ userOrgName = purview_organizationDO.getOrganizationName(); } } if(specialtyCode != null){ System_basicdataDO system_basicdataSpDO = (System_basicdataDO)Common.parseDBCache_Row(db_cacheSpecialityName, specialtyCode.toString(),System_basicdataDO.class.getName()); if(system_basicdataSpDO!=null){ certificateType += system_basicdataSpDO.getOptionsName(); } } if(gradeCode != null){ System_basicdataDO system_basicdataGradeDO = (System_basicdataDO)Common.parseDBCache_Row(db_cacheGradeName, gradeCode.toString(), System_basicdataDO.class.getName()); if(system_basicdataGradeDO != null){ certificateType += system_basicdataGradeDO.getOptionsName(); } } } // 单位名称 String userOrgNameXY = gw_certtempDO.getUserOrgXY(); LetterDTO userOrgNameDTO = getLetter(userOrgName,userOrgNameXY,"宋体","20","#000000"); letterDTO_list.add(userOrgNameDTO); // 有效期 String ExpiresXY = gw_certtempDO.getExpiresXY(); LetterDTO ExpiresDTO = getLetter("有效期至"+yeare+"年"+monthe+"月"+daye+"日",ExpiresXY,"宋体","20","#000000"); // LetterDTO ExpiresDTO = getLetter("截止日期:"+DateUtil.format(expiredDate, DateUtil.dateFormatYYYYMMDD),ExpiresXY,"宋体","20","#000000"); letterDTO_list.add(ExpiresDTO); // 年 String yearXY = gw_certtempDO.getYearXY(); LetterDTO yearXYDTO = getLetter(year,yearXY,"宋体","20","#000000"); letterDTO_list.add(yearXYDTO); // 月 String monthXY = gw_certtempDO.getMonthXY(); LetterDTO monthXYDTO = getLetter(month,monthXY,"宋体","20","#000000"); letterDTO_list.add(monthXYDTO); // 日 String dayXY = gw_certtempDO.getDayXY(); LetterDTO dayXYDTO = getLetter(day,dayXY,"宋体","20","#000000"); letterDTO_list.add(dayXYDTO); // 姓名 String userNameXY = gw_certtempDO.getUserNameXY(); LetterDTO userNameDTO = getLetter(userName,userNameXY,"宋体","20","#000000"); letterDTO_list.add(userNameDTO); // 身份证 String identityCardXY = gw_certtempDO.getIdentityCardXY(); LetterDTO identityCardDTO = getLetter(identityCard,identityCardXY,"宋体","20","#000000"); letterDTO_list.add(identityCardDTO); //专业岗位等级certificateTypeXY String certificateTypeXY = gw_certtempDO.getCertificateTypeXY(); LetterDTO certificateTypeDTO = getLetter(certificateType,certificateTypeXY,"宋体","20","#000000"); letterDTO_list.add(certificateTypeDTO); return letterDTO_list; } // 字体的名称 ,xy 坐标 , 字体类型 ,字体大小, 字体的颜色 public LetterDTO getLetter ( String name ,String xy ,String style ,String size ,String fontColor ){ LetterDTO letterDTO = new LetterDTO(); letterDTO.setLetter(name); Integer x = 0; Integer y = 0; if(xy != null){ xy.replace(',', ','); String[] str = xy.split(","); if(str.length > 1){ x = Integer.parseInt(str[0]); y = Integer.parseInt(str[1]); } else{ x = Integer.parseInt(str[0]); y = 0; } } letterDTO.setX(x); letterDTO.setY(y); Font font = Font.decode(style); font=font.deriveFont(Float.parseFloat(size));//font.deriveFont(float f)复制当前 Font 对象并应用新设置字体的大小 letterDTO.setFont(font); Color color=Color.decode(fontColor); letterDTO.setColor(color); return letterDTO ; } }
Class2 createJpg
package com.gsf.tool.image.util; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import javax.imageio.ImageIO; import com.company.erp.common.gw_certtemp.databean.Gw_certtempDO; import com.company.erp.system.bo.System_urlBO; import com.gsf.tool.image.dto.ImageDTO; import com.gsf.tool.image.dto.LetterDTO; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGEncodeParam; import com.sun.image.codec.jpeg.JPEGImageEncoder; public class CreateImage { /** * 根据提供的文字生成jpg图片 * * @param backJpgPath * String 背景图片路径 * @param imageDTO_list * 小图片dto(第个元素都是LetterDTO) list * @param letterDTO_list * 文字dto(第个元素都是ImageDTO_list) list * @param newJPGFileName * String 生成的新JPG图片名称 */ public boolean createJpg(String backImageFileName,ArrayList imageDTO_list, ArrayList letterDTO_list, String newJPGFileName) { boolean ret=false; try { // 宽度 高度 File backJpg_file = new File("E:\\companyERP_data\\resource\\url\\certificatePicture\\jpg\\certtemp\\zhengshu.jpg"); BufferedImage back_bufferdImage = ImageIO.read(backJpg_file); Graphics2D graphics2D = back_bufferdImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); //去除锯齿(当设置的字体过大的时候,会出现锯齿) if (letterDTO_list!=null) { for(int i=0;i<letterDTO_list.size();i++) { LetterDTO letterDTO=(LetterDTO) letterDTO_list.get(i); if ( (letterDTO!=null) && (letterDTO.getColor()!=null) && (letterDTO.getFont()!=null) ) graphics2D.setColor(letterDTO.getColor()); // 字的颜色 Font letter_Font=letterDTO.getFont(); graphics2D.setFont(letter_Font); FontMetrics letter_FontMetrics=graphics2D.getFontMetrics(letter_Font); int letter_Ascent=letter_FontMetrics.getAscent(); int letter_leading=letter_FontMetrics.getLeading(); graphics2D.drawString(letterDTO.getLetter(), letterDTO.getX(),letterDTO.getY()+letter_Ascent-letter_leading); //在指定坐标除添加文字 } } graphics2D.dispose();// 释放资源 if (imageDTO_list!=null) { for(int i=0;i<imageDTO_list.size();i++) { ImageDTO imageDTO=(ImageDTO) imageDTO_list.get(i); if ((imageDTO!=null) && imageDTO.getImageFileName()!=null) { File smallImage_file = new File(imageDTO.getImageFileName()); BufferedImage smallImage_bufferedImage = ImageIO.read(smallImage_file); int width = smallImage_bufferedImage.getWidth(); // 图片宽度 int height = smallImage_bufferedImage.getHeight(); // 图片高度 // 从图片中读取RGB int[] imageArray = new int[width * height]; imageArray = smallImage_bufferedImage.getRGB(0, 0, width, height,imageArray, 0, width); back_bufferdImage.setRGB(imageDTO.getX(), imageDTO.getY(), width, height,imageArray, 0, width); } } } FileOutputStream out = new FileOutputStream(newJPGFileName); // 指定输出文件 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(back_bufferdImage); param.setQuality(50f, true); encoder.encode(back_bufferdImage, param); // 存盘 out.flush(); out.close(); ret=true; } catch (Exception e) { System.out.println("createJpgByFont Failed!"); e.printStackTrace(); } return ret; } public static void main(String[] args) { ArrayList letterDTO_list=new ArrayList(); LetterDTO letterDTO=new LetterDTO(); letterDTO.setLetter("哈哈,终于可以合成图片了"); letterDTO.setX(70); letterDTO.setY(63); Font font = Font.decode("宋体"); font=font.deriveFont(Float.parseFloat("12"));//font.deriveFont(float f)复制当前 Font 对象并应用新设置字体的大小 letterDTO.setFont(font); Color color=Color.decode("#FF0000"); letterDTO.setColor(color); letterDTO_list.add(letterDTO); ArrayList imageDTO_list=new ArrayList(); ImageDTO imageDTO=new ImageDTO(); imageDTO.setImageFileName("C:\\jpg\\BlackUser.jpg"); imageDTO.setX(383); imageDTO.setY(22); imageDTO_list.add(imageDTO); CreateImage createImage = new CreateImage(); String backImageFileName = "C:\\jpg\\a.jpg"; String newJPGFileName="C:\\jpg\\a1.jpg"; createImage.createJpg(backImageFileName, imageDTO_list, letterDTO_list,newJPGFileName); } }
模板
合成后的图片
推荐阅读
-
java合成图片 博客分类: Java JavaSpringStrutsSUNServlet
-
基于SMB协议的共享文件读写 博客分类: Java
-
java读取纯真IP数据库QQwry.dat的源代码 博客分类: Java Java数据结构.netCacheJ#
-
在tomcat5.0以上版本中修改java代码而不用重启服务器 博客分类: Java JavaTomcatMyeclipseEclipseXML
-
读取配置文件java.util.Properties 博客分类: Java JavaWebService
-
HttpSessionListener和HttpSessionBindingListener的区别 博客分类: Java java
-
JSP中request.getParameter()乱码问题 博客分类: Java
-
更改main方法的内存 博客分类: Java
-
通过jcifs实现java访问网络共享文件 博客分类: Java 网络应用Java
-
《深入理解Java虚拟机》笔记之第3章 垃圾收集器与内存分配策略 博客分类: 读书笔记 垃圾收集JVM