Kaynağa Gözat

根据企业关键词或专家姓氏生成企业logo或头像

liyisong 4 yıl önce
ebeveyn
işleme
3c6f57411b

+ 2 - 1
.idea/compiler.xml

@@ -1,14 +1,15 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <project version="4">
   <component name="CompilerConfiguration">
+    <option name="USE_RELEASE_OPTION" value="false" />
     <annotationProcessing>
       <profile default="true" name="Default" enabled="true" />
       <profile name="Maven default annotation processors profile" enabled="true">
         <sourceOutputDir name="target/generated-sources/annotations" />
         <sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
         <outputRelativeToContentRoot value="true" />
-        <module name="ttc-app" />
         <module name="ttc" />
+        <module name="ttc-app" />
         <module name="ttc-backen" />
         <module name="ttc-im" />
       </profile>

+ 46 - 8
ttc-app/src/main/java/cn/ubitech/ttc/controller/DataToolsController.java

@@ -11,8 +11,8 @@ import cn.ubitech.ttc.model.researchcost.CheckParam;
 import cn.ubitech.ttc.model.user.RoleModel;
 import cn.ubitech.ttc.model.user.RolePageModel;
 import cn.ubitech.ttc.service.impl.datatools.DataEntryServiceImpl;
+import cn.ubitech.ttc.service.impl.datatools.ImgServiceImpl;
 import cn.ubitech.ttc.service.impl.datatools.InterviewDataEntryServiceImpl;
-import cn.ubitech.ttc.service.impl.label.LabelRecordServiceImpl;
 import cn.ubitech.ttc.service.impl.message.HomePageMessageService;
 import cn.ubitech.ttc.service.impl.mybaits.*;
 import cn.ubitech.ttc.service.impl.resource.ResourceServiceImpl;
@@ -21,6 +21,8 @@ import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiImplicitParam;
 import io.swagger.annotations.ApiImplicitParams;
 import io.swagger.annotations.ApiOperation;
+import lombok.NonNull;
+import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@@ -30,13 +32,9 @@ import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
 
 import javax.servlet.http.HttpServletResponse;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
+import javax.validation.constraints.NotNull;
+import java.io.*;
+import java.util.*;
 import java.util.List;
 import java.util.stream.Collectors;
 
@@ -69,6 +67,7 @@ import java.util.stream.Collectors;
 @RestController
 @RequestMapping("/data")
 @Api(description = "数据录入相关接口")
+@Slf4j
 public class DataToolsController {
     @Autowired
     private InterviewDataEntryServiceImpl interviewDataEntryService;
@@ -84,6 +83,9 @@ public class DataToolsController {
     private HomePageMessageService homePageMessageService;
     @Autowired
     private ImageSpiderCommon imageSpiderCommon;
+    @Autowired
+    private ImgServiceImpl imgService;
+
 
     /**
      * 根据角色获取所有模版
@@ -169,6 +171,7 @@ public class DataToolsController {
         ResultModel resultModel = new ResultModel();
         try {
             ConnectioninfoModel connectioninfoModel = Util.fromJson(Util.toJson(requestModel.getData()), ConnectioninfoModel.class);
+            log.info("connectioninfoModel:{}" + connectioninfoModel);
             String pagetitle = requestModel.getPagetitle();
             //通过ISINSERTFLAG来判断是新建还是编辑
             Util.judgeIsInsertFalg(connectioninfoModel);
@@ -1553,4 +1556,39 @@ public class DataToolsController {
         return resultModel;
     }
 
+
+    @GetMapping("/keywordTurnImg/{keyword}/{restype}")
+    @ApiOperation(value = "没有上传头像的公司将关键词转为图片在上传", notes = "没有上传头像的公司将关键词转为图片在上传接口")
+    @ApiImplicitParams({
+            @ApiImplicitParam(name = "keyword", paramType = "path", dataType = "String", value = "关键词"),
+            @ApiImplicitParam(name = "restype", paramType = "path", dataType = "String", value = "区分哪个库")
+    })
+    public ResultModel keywordTurnImg (@PathVariable String keyword,@PathVariable @NotNull String restype){
+
+        ResultModel resultModel = new ResultModel();
+        try {
+            String newCode = imgService.drawPicture(keyword,restype);
+            resultModel.setCode(Constant.INTERFACE_STATUS_CODE_3350);
+            resultModel.setData(newCode);
+        } catch (Exception e) {
+            resultModel.setCode(Constant.INTERFACE_STATUS_CODE_3351);
+            resultModel.setData(e.toString());
+            e.printStackTrace();
+        }
+        return resultModel;
+    }
+
+    @GetMapping("/resolverExcel")
+    @ApiOperation(value = "解析excel文件", notes = "解析excel文件")
+    public ResultModel resolverExcel(){
+        ResultModel resultModel = new ResultModel();
+        try {
+            imgService.resolverExcel("C:\\Users\\25075\\Desktop\\logo.xlsx");
+        } catch (Exception e) {
+            resultModel.setCode(Constant.INTERFACE_STATUS_CODE_3351);
+            resultModel.setData(e.toString());
+            e.printStackTrace();
+        }
+        return resultModel;
+    }
 }

+ 1 - 1
ttc-app/src/main/resources/application-dev.yml

@@ -49,7 +49,7 @@ fdfs:
 push:
   common:
     dir:
-      base: F:\\push
+      base: E:\\push
       # 上传文件存储文件夹
       upload: ${push.common.dir.base}\\upload\\
       imag: ${push.common.dir.base}\\upload\\img\\

+ 286 - 0
ttc-backen/src/main/java/cn/ubitech/ttc/service/impl/datatools/ImgServiceImpl.java

@@ -0,0 +1,286 @@
+package cn.ubitech.ttc.service.impl.datatools;
+
+import cn.ubitech.ttc.common.ElasticSearchUtil;
+import cn.ubitech.ttc.dao.*;
+import cn.ubitech.ttc.entity.Connectioninfo;
+import cn.ubitech.ttc.entity.OrganizationInfo;
+import cn.ubitech.ttc.entity.Resourcelibrary;
+import cn.ubitech.ttc.model.common.ElasticSearchTTCModel;
+import cn.ubitech.ttc.service.impl.resourceChoice.ResouceChoiceServiceImpl;
+import com.baomidou.mybatisplus.mapper.EntityWrapper;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.poi.ss.usermodel.CellType;
+import org.apache.poi.xssf.usermodel.*;
+import org.csource.fastdfs.*;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
+import org.springframework.data.elasticsearch.core.query.UpdateQuery;
+import org.springframework.mock.web.MockMultipartFile;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.multipart.MultipartFile;
+import sun.font.FontDesignMetrics;
+
+import javax.imageio.ImageIO;
+import java.awt.*;
+import java.awt.font.FontRenderContext;
+import java.awt.font.TextLayout;
+import java.awt.geom.AffineTransform;
+import java.awt.image.BufferedImage;
+import java.io.*;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
+
+
+/**
+ * @author lys
+ * @create 2021-08-05 11:43
+ */
+@Service
+@Slf4j
+public class ImgServiceImpl {
+
+    @Autowired
+    private ConnectioninfoMapper connectioninfoMapper;
+
+    @Autowired
+    private OrganizationInfoMapper organizationInfoMapper;
+
+    @Autowired
+    private ResourcelibraryMapper resourcelibraryMapper;
+
+    @Autowired
+    private ResouceChoiceServiceImpl resouceChoiceService;
+
+    @Autowired
+    private ElasticSearchUtil elasticSearchUtil;
+
+    @Autowired
+    private ElasticsearchTemplate elasticsearchTemplate;
+
+    public String drawPicture(String keyword,String restype) {
+
+        //设置背景色
+        BufferedImage img = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);//构造一个类型为预定义图像类型之一的 BufferedImage。
+        Graphics2D g2d = img.createGraphics();
+        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f));  // 1.0f为透明度 ,值从0-1.0,依次变得不透明
+        if ("6".equals(restype)) {
+            g2d.setColor(new Color(106,136,255));
+        } else if ("8".equals(restype)){
+            g2d.setColor(new Color(245,245,245));
+        }
+        g2d.setBackground(new Color(106,136,255));
+        g2d.fillRect(0, 0, img.getWidth(), img.getHeight());//填充制定的矩形
+        //设置文字居中,描边
+        drawKeyword(g2d, keyword,restype);
+
+        try {
+            ByteArrayOutputStream out = new ByteArrayOutputStream();
+            ImageIO.write(img,"png",out);
+            MultipartFile multipartFile = new MockMultipartFile("pic1.jpg", out.toByteArray());
+            return uploadImg(multipartFile);
+
+            //保存到本地
+//            ImageIO.write(img,"jpg",new File("E:\\IDEA_Workspace\\ttc_5.0\\ttc-app\\src\\main\\resources\\img\\1.jpg"));
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+
+    private void drawKeyword(Graphics2D g2d, String keyword,String restype) {
+        //设置文字居中,描边
+        Font font;
+        if (restype.equals("8")) {
+            font = new Font("宋体", Font.BOLD, 100);
+        } else {
+            font = new Font("宋体 ", Font.BOLD, 56);
+        }
+        FontMetrics fm = g2d.getFontMetrics(font);
+        int testWith = fm.stringWidth(keyword);
+        int widthX = (300 - testWith) / 2;
+        int descent = fm.getDescent();
+        int ascent = fm.getAscent();
+        int height = (300 + ascent - descent) / 2;
+
+        FontRenderContext frc = g2d.getFontRenderContext();
+
+        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
+        TextLayout t1 = new TextLayout(keyword, font, frc);
+        Shape sha = t1.getOutline(AffineTransform.getTranslateInstance(widthX, height));
+        g2d.setStroke(new BasicStroke(4.0f));
+
+        if ("6".equals(restype)) {
+            g2d.setColor(Color.white);
+            g2d.draw(sha);
+            g2d.setColor(Color.white);
+        } else if ("8".equals(restype)) {
+            g2d.setColor(Color.BLACK);
+            g2d.draw(sha);
+            g2d.setColor(Color.BLACK);
+        }
+        g2d.fill(sha);
+//        writefont(font, keyword, 150, 50, g2d, 72, 25, Color.white);
+        g2d.dispose();
+    }
+
+    private void writefont(Font font, String content, Integer contentWidth, Integer contentHeight, Graphics2D graphics, int x, int y, Color color) {
+        int rowWidth = 0;   //已用字当前行宽度
+        int tempWidth;
+        String lineString = "";
+        List<String> contentLineList = new ArrayList<>();
+        List<Integer> contentLineWidth = new ArrayList<>();
+
+        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
+        int fontHeight = metrics.getHeight();
+        //每个新增字体宽度增加后如果超过文本框宽度就换行,没超过就不换行
+        for (int i = 0; i < content.length(); i++) {
+            tempWidth = rowWidth;//存之前的情况
+            rowWidth = rowWidth + metrics.charWidth(content.charAt(i));
+
+            if (rowWidth > contentWidth) {
+                contentLineList.add(lineString);
+                contentLineWidth.add(tempWidth);
+                rowWidth = metrics.charWidth(content.charAt(i));
+                lineString = "" + content.charAt(i);
+            } else {
+                lineString = lineString + content.charAt(i);
+            }
+
+            //最后一个字
+            if (i == content.length() - 1) {
+                contentLineList.add(lineString);
+                contentLineWidth.add(rowWidth);
+            }
+        }
+        graphics.setFont(font);
+        graphics.setColor(color);
+        //图片上写入每行文字  每行居中实现
+        for (int i = 0; i < contentLineList.size(); i++) {
+            graphics.drawString(contentLineList.get(i), (contentWidth - contentLineWidth.get(i)) / 2 + x, fontHeight + i * fontHeight + y);
+        }
+    }
+
+    public String uploadImg(MultipartFile multipartFile) {
+
+        try {
+            TrackerClient trackerClient = new TrackerClient();
+            TrackerServer trackerServer = trackerClient.getConnection();
+            StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
+            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storeStorage);
+            String originalFilename = multipartFile.getOriginalFilename();
+//            String name = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
+            String name = originalFilename + "png";
+            return storageClient1.upload_file1(multipartFile.getBytes(), name, null);
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+
+
+    @Transactional
+    //解析excel文件
+    public void resolverExcel(String filePath) throws Exception {
+        File file = new File(filePath);
+        if (!file.exists()){
+            throw new Exception("文件不存在!");
+        }
+        InputStream in = new FileInputStream(file);
+        // 读取整个Excel
+        XSSFWorkbook sheets = new XSSFWorkbook(in);
+        // 获取第一个表单Sheet
+        XSSFSheet sheetAt = sheets.getSheetAt(0);
+        ArrayList<Map<String, String>> list = new ArrayList<>();
+        //默认第一行为标题行,i = 0
+        XSSFRow titleRow = sheetAt.getRow(0);
+        // 循环获取每一行数据
+        for (int i = 1; i < sheetAt.getPhysicalNumberOfRows(); i++) {
+            XSSFRow row = sheetAt.getRow(i);
+            LinkedHashMap<String, String> map = new LinkedHashMap<>();
+            // 读取每一格内容
+            for (int index = 0; index < row.getPhysicalNumberOfCells(); index++) {
+                XSSFCell titleCell = titleRow.getCell(index);
+                XSSFCell cell = row.getCell(index);
+                // cell.setCellType(XSSFCell.CELL_TYPE_STRING); 过期,使用下面替换
+                cell.setCellType(CellType.STRING);
+                if (cell.getStringCellValue().equals("")) {
+                    continue;
+                }
+                map.put(getString(titleCell), getString(cell));
+            }
+            if (map.isEmpty()) {
+                continue;
+            }
+            list.add(map);
+        }
+        list.forEach(l ->{
+            if (!"有".equals(l.get("keyword"))) {
+                List<Resourcelibrary> resourcelibraries = resourcelibraryMapper.selectList(new EntityWrapper<Resourcelibrary>()
+                        .eq("title", l.get("name"))
+                        .eq("comefrom", "320117400")
+                        .eq("restype", 6));
+                List<Connectioninfo> connectioninfos = connectioninfoMapper.selectList(new EntityWrapper<Connectioninfo>()
+                        .eq("title", l.get("name"))
+                        .eq("node", 320117400));
+                List<OrganizationInfo> organizationInfos = organizationInfoMapper.selectList(new EntityWrapper<OrganizationInfo>()
+                        .eq("name", l.get("name")));
+                String logo = drawPicture(l.get("keyword"),"6");
+                System.out.println(logo);
+                if (CollectionUtils.isNotEmpty(resourcelibraries)) {
+                    resourcelibraries.get(0).setLogo(logo);
+                    resourcelibraryMapper.updateById(resourcelibraries.get(0));
+
+                    ElasticSearchTTCModel elasticSearchTTCModel = resouceChoiceService.getResourceByResourceId(resourcelibraries.get(0).getId());
+                    if (elasticSearchTTCModel != null && !"0".equals(elasticSearchTTCModel.getUnique())) {
+                        UpdateQuery updateQuery = new UpdateQuery();
+                        updateQuery.setId(elasticSearchTTCModel.getSnowflakeID());
+                        updateQuery.setIndexName(elasticSearchUtil.getES_INDEXNAME());
+                        updateQuery.setType(elasticSearchUtil.getES_TYPENAME());
+                        updateQuery.setDoUpsert(true);
+                        updateQuery.setClazz(elasticSearchTTCModel.getClass());
+                        try {
+                            updateQuery.setUpdateRequest(new UpdateRequest().doc(jsonBuilder().startObject().field("logo", logo).endObject()).refresh(true).retryOnConflict(5));
+                            elasticsearchTemplate.update(updateQuery);
+                        } catch (IOException e) {
+                            throw new RuntimeException("根据关键字创建logo时,修改索引库数据时异常");
+                        }
+                    }
+                }
+                if (CollectionUtils.isNotEmpty(connectioninfos)) {
+                    connectioninfos.get(0).setLogo(logo);
+                    connectioninfoMapper.updateById(connectioninfos.get(0));
+                }
+                if (CollectionUtils.isNotEmpty(organizationInfos)) {
+                    organizationInfos.get(0).setLogo(logo);
+                    organizationInfoMapper.updateById(organizationInfos.get(0));
+                }
+
+            }
+        });
+    }
+
+    private static String getString(XSSFCell xssfCell) {
+        if (xssfCell == null) {
+            return "";
+        }
+        if (xssfCell.getCellTypeEnum() == CellType.NUMERIC) {
+            return String.valueOf(xssfCell.getNumericCellValue());
+        } else if (xssfCell.getCellTypeEnum() == CellType.BOOLEAN) {
+            return String.valueOf(xssfCell.getBooleanCellValue());
+        } else {
+            return xssfCell.getStringCellValue();
+        }
+    }
+
+}

+ 16 - 0
ttc-backen/src/main/java/cn/ubitech/ttc/service/impl/datatools/InterviewDataEntryServiceImpl.java

@@ -215,6 +215,8 @@ public class InterviewDataEntryServiceImpl implements IDataEntryService {
     private SubsidiesListMapper subsidiesListMapper;
     @Autowired
     private SubsidiesListService subsidiesListService;
+    @Autowired
+    private ImgServiceImpl imgService;
 
 
     @Override
@@ -579,6 +581,11 @@ public class InterviewDataEntryServiceImpl implements IDataEntryService {
     @Transactional
     public ConnectioninfoModel insertOrUpdate(ConnectioninfoModel connectioninfoModel, String node, long pagecode, String pagetitle) {
         log.info("param connectioninfoModel:{}",connectioninfoModel.getOrgcontent());
+        if (connectioninfoModel.getOrglogo() == null && connectioninfoModel.getOrganizationInfo().getLogo() == null) {
+//            String logo = imgService.drawPicture("");
+//            connectioninfoModel.setOrglogo(logo);
+//            connectioninfoModel.getOrganizationInfo().setLogo(logo);
+        }
         if (connectioninfoModel.getOrganizationInfo().getId() == null) {
             log.info("connectioninfoModel.getOrganizationInfo().getId() == null ...");
             List<OrganizationInfo> orglist = organizationInfoMapper.getOrgListByNode(connectioninfoModel.getOrganizationInfo().getName(), node);
@@ -1243,6 +1250,15 @@ public class InterviewDataEntryServiceImpl implements IDataEntryService {
      */
     public CompanyHighleveltalentsLk insertOrUpdate(CompanyHighleveltalentsLk companyHighleveltalentsLk, String node) {
         if (StringUtils.isNotEmpty(companyHighleveltalentsLk.getName())) {
+
+            //todo lys
+            //丽水节点的企业库和专家库在在录入时未上传logo或者头像自动生成
+            if ("320117400".equals(node) && ("6".equals(companyHighleveltalentsLk.getRestype()) || "8".equals(companyHighleveltalentsLk.getRestype()))) {
+                String surname = companyHighleveltalentsLk.getName().trim().substring(0, 1);
+                String logo = imgService.drawPicture(surname,companyHighleveltalentsLk.getRestype());
+                companyHighleveltalentsLk.setPhoto(logo);
+            }
+
             String claid = getClaid(node, companyHighleveltalentsLk.getCreator());
             if (companyHighleveltalentsLk.getId() == null || companyHighleveltalentsLk.getId() == 0) {
                 companyHighleveltalentsLk.setLinktype(getTypecode(companyHighleveltalentsLk.getConnid()));