java上传带旋转角度的图片旋转问题

来源:互联网 发布:淘宝被禁言了怎么解除 编辑:程序博客网 时间:2024/05/21 17:17

学习笔记-java上传带旋转角度的图片旋转问题

最近在上传由ios拍摄的照片的时候发现有些图片在手机里显示的是正确的方向,但是上传到网页上显示的时候会自动进行了旋转,改变了方向。这是由于在用手机进行拍摄时,根据拿手机的角度不同,照片会在属性信息里保存一个旋转角度,在我们上传图片时,系统会根据图片的旋转角度自动旋转,但是大部分时候,这并不是我们需要的,所以我们就要根据这个旋转角度将图片旋转到正确的方向。我在做图片上传旋转的时候是以下步骤:

  • 上传图片
  • 旋转图片
  • 图片回显

具体操作

图片上传

代码块

jsp图片上传标签:

<label>图片</label><input id="file" name="file" type="file"/><input type="button" value="提交"/>

图片上传controller

代码块

FileController:

@RequestMapping(value="/file",method=RequestMethod.POST,produces="text/html;charset=UTF-8")    public @ResponseBody String fileUpload(            @RequestParam MultipartFile file,HttpServletRequest request){        System.out.println("走到这了");        String root = request.getSession().getServletContext().getRealPath("");        System.out.println(root);        String path = "";        if(!file.isEmpty()){            String uuid = UUID.randomUUID().toString().replaceAll("-", "");            String contentType = file.getContentType();            System.out.println(file.getOriginalFilename());            System.out.println(contentType);            String filename = contentType.substring(contentType.indexOf("/")+1);            System.out.println(filename);            path="image/"+uuid+"."+filename;            try {                file.transferTo(new File(root+"\\"+path));            } catch (IllegalStateException | IOException e) {                System.out.println(e.getMessage());            }        }    return path;          }

图片旋转:

在图片旋转之前,先获取图片的旋转角度。这个旋转角度在图片的exif信息里,这个信息里包括拍摄经纬度,图片规格,旋转角度,曝光度及其他信息。读取图片的exif信息要使用com.drew.metadata下的Metadata:

代码块

FileUtil:

public static Map<String,Object> getExif(String fileName){        Map<String,Object> map = new HashMap<String,Object>();        File file = new File(fileName);        try {            Metadata metadata = ImageMetadataReader.readMetadata(file);            map = printExif(file,metadata);        } catch (ImageProcessingException e) {            System.out.println(e.getMessage());        } catch (IOException e) {            System.out.println(e.getMessage());        }        return map;    }    //获取exif信息,将旋转角度信息拿到    private static Map<String,Object> printExif(File file,Metadata metadata){        Map<String,Object> map = new HashMap<String,Object>();        String tagName = null;        String desc = null;        for(Directory directory : metadata.getDirectories()){            for(Tag tag : directory.getTags()){                tagName = tag.getTagName();                desc = tag.getDescription();              /*  System.out.println(tagName+","+desc);*/                if(tagName.equals("Orientation")){                    map.put("Orientation", desc);                }            }        }           return map;    }    public static int getAngle(Map<String,Object> map){        String ori = map.get("Orientation").toString();        int ro = 0;        if(ori.indexOf("90")>=0){            ro=1;        }else if(ori.indexOf("180")>=0){            ro=2;        }else if(ori.indexOf("270")>=0){            ro=3;        }        return ro;    }

获取到旋转角度之后,就要进行图片旋转。图片旋转用java.awt.Graphics2D下的Graphics2D

代码块

ImageUtil:

public static BufferedImage getBufferedImg(BufferedImage src,String url,int width,int height,int ro){        int angle = (int)(90*ro);        int type = src.getColorModel().getTransparency();        int wid = width;        int hei = height;        if(ro%2!=0){            int temp = width;            width = height;            height = temp;        }        Rectangle re = new Rectangle(new Dimension(width, height));        BufferedImage BfImg = null;        BfImg = new BufferedImage(re.width, re.height, type);        Graphics2D g2 = BfImg.createGraphics();        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);        /*g2.translate((re.width-width)/2, (re.height-height)/2);*/        g2.rotate(Math.toRadians(angle),re.width/2,re.height/2);        g2.drawImage(src,(re.width-wid)/2,(re.height-hei)/2,null);        g2.dispose();        return BfImg;       }

图片旋转角度工具类以及旋转工具类都写好之后,就要在FileController中去调用。

代码块

FileController中加入代码:

 String url = root+"\\"+path;        System.out.println(url);        File img = new File(url);        FileUtil.getExif(url);        int angle =  FileUtil.getAngle( FileUtil.getExif(url));        System.out.println(FileUtil.getExif(url));        System.out.println(angle);        //-----------------        InputStream is=null;        BufferedImage src=null;        try {            is = new FileInputStream(img);            src = ImageIO.read(is);        } catch (FileNotFoundException e) {            System.out.println(e.getMessage());        } catch (IOException e) {            System.out.println(e.getMessage());        }        //旋转        BufferedImage bf = ImageUtil.getBufferedImg(src,url, getWidth(img), getHeight(img), angle);        System.out.println(bf.getWidth()+","+bf.getHeight());               /*BufferedImage bft = ImageTest.draw(url);        BufferedImage bf = ImageTest.rotate(bft);*/        try {            ImageIO.write(bf, "jpg", new File(root+"\\"+path));        } catch (IOException e) {            System.out.println(e.getMessage());        }

在调用方法的时候会用到上传图片的原始尺寸,以下为获取图片尺寸的方法

代码块

FileController中加入代码:

 public static int getHeight(File file){        InputStream is = null;        BufferedImage src = null;        int height = -1;        try {            is = new FileInputStream(file);            src = ImageIO.read(is);            height = src.getHeight();        } catch (FileNotFoundException e) {            System.out.println(e.getMessage());        } catch (IOException e) {            System.out.println(e.getMessage());        }        return height;    }    public static int getWidth(File file){        InputStream is = null;        BufferedImage src = null;        int width = -1;        try {            is = new FileInputStream(file);            src = ImageIO.read(is);            width = src.getWidth();        } catch (FileNotFoundException e) {            System.out.println(e.getMessage());        } catch (IOException e) {            System.out.println(e.getMessage());        }        return width;    }

图片回显

在旋转图片结束之后,将得到的图片在前台显示,因为我想异步,普通的jquery的ajax用来异步图片回显比较麻烦,所以这里我用了ajaxfileupload去处理。在下载ajaxfileupload.js的时候应该注意要与jquery的版本一致,否则会发生错误。

代码块

jsp代码:

<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script><script type="text/javascript" src="js/ajaxfileupload.js"></script><script type="text/javascript">$(function () {    $(":button").click(function () {        ajaxFileUpload();    })})function ajaxFileUpload() {    $.ajaxFileUpload({            url: 'file', //用于文件上传的服务器端请求地址            secureuri: false, //是否需要安全协议,一般设置为false            fileElementId: 'file', //文件上传域的ID            dataType:'text',            success: function (data, status)  //服务器成功响应处理函数            {                $("#image").attr("src", data);            },            error: function (data, status, e)//服务器响应失败处理函数            {                alert(e);            }        });    return false;}</script>

感悟

以前没有接触过图像处理,这次通过查阅资料,实现了图片旋转。希望自己在以后的工作学习中,能够有所进步。

3 0
原创粉丝点击