java获取图片信息

		<!--exif读取-->
        <dependency>
            <groupId>com.drewnoakes</groupId>
            <artifactId>metadata-extractor</artifactId>
            <version>2.11.0</version>
        </dependency>
        <!--制作缩略图-->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>
package com.bdkj.cruise.controller;

import com.bdkj.cruise.model.Media;
import com.bdkj.cruise.service.MediaService;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;


import net.coobird.thumbnailator.Thumbnails;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@EnableAutoConfiguration
@RequestMapping("/imagemap")
public class HomeController {
    @Autowired
    private MediaService mediaService;

    @RequestMapping(value = "/userList")
    public String userSetting() {
        return "media";
    }

    /**
     * 获取照片信息
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getImages")
    public void getBou(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String shootingTime = "2018-09-28";
        String riverName="长江";
        List<Media> media = mediaService.selectBySTAndRName(shootingTime,riverName);
        Map<String, List<Media>> map = new HashMap<String, List<Media>>();

        int k=0;
        if (media.size()>20){ k=20; }else {k=media.size();}
        for (int i=0;i<k;i++){
            String fileNP=media.get(i).getFilepath()+"\\"+media.get(i).getFilename();
            StringBuilder sb=new StringBuilder(fileNP);
            sb.insert(sb.length()-4,"_thum");
            fileNP=sb.toString();
            File file=new File(fileNP);
            if (!file.exists()){
                Thumbnails.of(media.get(i).getFilepath()+"\\"+media.get(i).getFilename())
                        .scale(0.3f)
                        .outputQuality(0.2f)
                        .toFile(fileNP);
            }
        }
        map.put("media", media);
        JSONObject json = JSONObject.fromObject(map);

        try {
            response.setContentType("text/html; charset=utf-8");
            response.getWriter().print(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存照片信息到数据库
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/mediaSave")
    public void mediaSave(HttpServletRequest request, HttpServletResponse response)  throws Exception {
        /*String newUuid = "";*/
        JSONObject jsonData = new JSONObject();
        Map<String, String[]> paramMap = request.getParameterMap();
        for (String name : paramMap.keySet()) {
            String[] values = paramMap.get(name);
            jsonData.put(name, StringUtils.join(values));
        }
        Media media = new Media();
        media = (Media) JSONObject.toBean(jsonData, Media.class);
        /*newUuid = java.util.UUID.randomUUID().toString();
        media.setUuid(newUuid);*/
        String folderpath = "G:\\sunxiang";        //要遍历的路径
        File file = new File(folderpath);        //获取其file对象
        media.setFolderpath(folderpath);//输入的文件夹地址
        func(file,media,mediaService);


        int p = 0, k = -1;

        JSONObject re = new JSONObject();
        if (p != 0) {
            re.put("state", 2); // 重复
        } else {
            if (k == 1) {
                re.put("state", 0); // 成功保存
            } else {
                re.put("state", 1); // 保存失败
            }
        }
        try {
            response.setContentType("text/html; charset=utf-8");
            response.getWriter().print(re);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 递归遍历
     * @param file
     */
    private static void func(File file,Media media,MediaService mediaService) throws Exception  {
        File[] fs = file.listFiles();
        for (File f : fs) {
            if (f.isDirectory())    //若是目录,则递归打印该目录下的文件
            {
                func(f,media,mediaService);
            }
            if (f.isFile())        //若是文件,直接打印
            {
                //System.out.println(f);
                String fName=f.toString().trim();
                String name=fName.substring(fName.lastIndexOf("\\")+1);//文件名称
                media.setFilename(name);
                String newUuid = java.util.UUID.randomUUID().toString();
                media.setUuid(newUuid);
                String filepath=fName.substring(0,fName.lastIndexOf("\\"));//文件路径
                media.setFilepath(filepath);
                File jpegFile = new File(f.toString().replace("\\","\\\\"));
                Metadata metadata = JpegMetadataReader.readMetadata(jpegFile);
                for(Directory directory : metadata.getDirectories()){
                    for(Tag tag : directory.getTags()){
                        //纬度
                        if ("GPS Latitude".equals(tag.getTagName())){
                            media.setB(angleTool(tag.getDescription()));
                        }
                        //经度
                        if ("GPS Longitude".equals(tag.getTagName())){
                            media.setL(angleTool(tag.getDescription()));
                        }
                        //高度
                        if ("GPS Altitude".equals(tag.getTagName())){
                            media.setH(Double.parseDouble(tag.getDescription().substring(0,tag.getTagName().lastIndexOf(" "))));
                        }
                        //拍摄时间
                        if ("Date/Time".equals(tag.getTagName())){
                            String date=tag.getDescription();
                            char[] status=date.toCharArray();
                            status[4]='-';
                            status[7]='-';
                            date=Arrays.toString(status).replaceAll("[\\[\\]\\s,]", "");
                            StringBuffer buf=new StringBuffer();
                            buf.append(date);
                            buf.insert(10," ");
                            date=buf.toString();
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            media.setTime(sdf.parse(date));
                        }
                    }
                }
                mediaService.insertSelective(media);
            }
        }
    }

    private static double angleTool(String angStr){
        double dd,mm,ss;
        angStr=angStr.replace("°","|");
        angStr=angStr.replace("'","|");
        angStr=angStr.replace("\"","");
        angStr=angStr.replace(" ","");
        String[] angObj=angStr.split("\\|");
        if (angObj.length ==3){
            dd=Double.parseDouble(angObj[0]);
            mm=Double.parseDouble(angObj[1])/60;
            ss=Double.parseDouble(angObj[2])/3600;
            return  (dd+mm+ss);
        } else{
            return 0.00;
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值