应业务要求,批量制作图片并导出到本地,之前尝试了几次,走出了一个误区,不能再java后台直接将文件上传到客户端本地,后来又发现浏览器不能一次导出多张图片,于是,只能制作多个图片,先上传到服务器,再打成压缩包导出到浏览器,终于达到了想要的效果。
步骤则是:先把所要制作的内容和文字结合在一起,传输到服务器后,直接压缩到本地。以下是相关代码:
/**
* 制作图片
* @param benisonTemplateBO:模板对象(包含抬头内容,字体,颜色,主体内容,字体,颜色,落款内容,字体,颜色)
* @param order 订单map对象(包括订单编号,落款人姓名,祝福人姓名等,用来动态替换图片上的文字信息)
* @param time 当前时间(自定义文件夹用)
*/
public Map
makeImg(BenisonTemplateBO benisonTemplateBO,Dto order,String time){
Map
map = new HashMap
();
String newImgUrl = null;
try {
//设置抬头的字体
FontText titleText = new FontText(order.getAsString("bless_name"),benisonTemplateBO.getTitleColour(), Integer.valueOf(benisonTemplateBO.getTitleSize()), benisonTemplateBO.getTitleType());
//设置主体内容的字体
FontText bodyText = new FontText(benisonTemplateBO.getRuleContent(),benisonTemplateBO.getBodyColour(), Integer.valueOf(benisonTemplateBO.getBodySize()), benisonTemplateBO.getBodyType());
//设置落款内容的字体
FontText tailText = new FontText(order.getAsString("write_name"),benisonTemplateBO.getTailColour(), Integer.valueOf(benisonTemplateBO.getTailSize()), benisonTemplateBO.getTailType());
//拷贝图片到另一个文件夹
String path = CommonUtil.exportUploadFilePath()+time+"/";//获取properties属性中导出后的文件路径
logger.info("<=========path:{}=========>",path);
map.put("path", path);
//动态获取文件格式
String fileFormat =benisonTemplateBO.getImgUrl().substring(benisonTemplateBO.getImgUrl().indexOf(".")+1,benisonTemplateBO.getImgUrl().length());
logger.info("<=========fileFormat:{}=========>",fileFormat);
String fileName = order.get("order_code")+"."+fileFormat;//新的文件名
//如果没有文件夹,则新创建一个。
Boolean dirFlag = createDir(path);
if(!dirFlag){
map.put("result", "false");
map.put("msg", "创建文件夹失败");
return map;
}
//拷贝图片为了不改变原图片
newImgUrl = copyFile(CommonUtil.uploadFilePath()+benisonTemplateBO.getImgUrl(),path+fileName);
if(StringUtils.isEmpty(newImgUrl)){
map.put("result", "false");
map.put("msg", "拷贝文件失败");
return map;
}
//制作图片(注释是另一种,只支持JPG图像)
// InputStream is = new FileInputStream(newImgUrl);
// JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(is); //通过JPEG图象流创建JPEG数据流解码器 (只能解析JPEGt图片)
// BufferedImage buffImg = jpegDecoder.decodeAsBufferedImage(); //解码当前JPEG数据流,返回BufferedImage对象
File file = new File(newImgUrl);
Image image = ImageIO.read(file);//得到带有图片属性的对象
BufferedImage buffImg =ImageIO.read(file);
//创建画笔
Graphics2D g = buffImg.createGraphics();
// g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f)); // 1.0f为透明度 ,值从0-1.0,依次变得不透明(没有用到)
//写抬头
g.setColor(getColor(titleText.getWm_text_color()));
g.setBackground(Color.white);
g.setFont(getFont(titl