Java上传图片、剪裁图片、 imgareaselect +BufferedImage + BufferedImage

来源:互联网 发布:jdk 8u60 linux x32 编辑:程序博客网 时间:2024/05/01 05:09

我当时用到的场景:有需求,上传用户头像,用户还可以自己裁剪图片。首先来个示例,然后开始正式进入主题。

前台:1.imageSelect.jsp

    <body>
        <script type="text/javascript">
            function preview(img, selection) {
                if (!selection.width || !selection.height)
                    return;

                var scaleX = 100 / selection.width;
                var scaleY = 100 / selection.height;

                $('#preview img').css({
                    width : Math.round(scaleX * 300),
                    height : Math.round(scaleY * 300),
                    marginLeft : -Math.round(scaleX * selection.x1),
                    marginTop : -Math.round(scaleY * selection.y1)
                });
            }

            $(function() {
                $('#photo').imgAreaSelect({
                    aspectRatio : '1:1',
                    handles : true,
                    fadeSpeed : 200,
                    onSelectChange : preview
                });
            });
        </script>
        <div class="frame" style="width: 300px; height: 300px;float:left;margin-right:50px">
            <img id="photo" src="files/flower2.jpg">
        </div>
        <div id="preview" style="width: 100px; height: 100px; overflow: hidden;">
            <img src="files/flower2.jpg" style="width: 100px; height: 100px;">
        </div>
    </body>

后台:2.imageTool.java

public class ImgTool {
    private BufferedImage subImg;
    /**
     * 截图
     * @param srcPath
     * @param startX
     * @param startY
     * @param width
     * @param height
     */
    public void cut(String srcPath,int startX,int startY,int width,int height){
        try {
            BufferedImage bufImg = ImageIO.read(new File(srcPath));
            subImg = bufImg.getSubimage(startX, startY, width, height);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 保存截图。
     * @param bufImg
     * @param imgType
     * @param tarPath
     */
    public void save(String imgType,String imgName,String tarPath,int width,int height){
        try {/**压缩图片为指定尺寸*/
            if(subImg.getWidth()!=width || subImg.getHeight()!=height){
                BufferedImage tempImg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
                tempImg.getGraphics().drawImage(subImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0,null);
                ImageIO.write(tempImg, imgType, new File(tarPath+"/"+imgName));
            }else{
                ImageIO.write(subImg,imgType,new File(tarPath+"/"+imgName));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


现在正是开始了。这是我在项目中的写法,希望能对大家有帮助:

1.先将 BufferedImage转换成InputStream,将文件接收到并裁减成自己想要的大小规格。

2.然后完成后 InputStream转换成 BufferedImage

ByteArrayOutputStream os = new ByteArrayOutputStream();  
 ImageIO.write(tempImg, "gif", os);  
 InputStream inputStrem = new ByteArrayInputStream(os.toByteArray());

3,。最后上传到ftp文件服务器:

fileMessage = sftpFileOper.upSftpFileCommon(filename, ins, path);//完成数据提交上传到ftp服务器


public JSONObject setUserHead(Map<String, Object> urlParams,Map<String, String> reqParams,
            TuUser tuUser,TuAccountAvatarMapper  avatarMpper){
        JSONObject jsonObj = new JSONObject();
        //reqParams里面获取的参数:startX,startY, width, height, imgName, imgType
                          //:String srcPath,int startX,int startY,int width,int height
        
        //获取源文件流:String srcPath;
        //配置文件中读取ftp上的保存路径:String tarPath
        Map<String , Object> map = new HashMap<>();
        
        MultipartFile[] files = (MultipartFile[]) urlParams.get("file");
        int startX = Integer.parseInt(reqParams.get("startX"));
        int startY = Integer.parseInt(reqParams.get("startY"));
        int width = Integer.parseInt(reqParams.get("width"));
        int height = Integer.parseInt(reqParams.get("height"));
        String imgName = "";//图片名称
        String tarPath = "";//图片最终保存的路径
        
        MultipartFile file = null;
        int FileLength = files.length;
         if (files != null && FileLength > 0) {
             //循环获取file数组中得文件
            for (int i = 0; i < FileLength; i++) {
                file = files[i];
                imgName = file.getOriginalFilename();//上传的文件名称
                InputStream input;
                try {
                    input = file.getInputStream();
                    BufferedImage bufImg = ImageIO.read(input);
                    save( "path", bufImg, startX, startY , imgName, tarPath, width, height, tuUser.getUsername(), avatarMpper,  reqParams);
                    jsonObj.put("code", 0);
                      jsonObj.put("msg", "获取头像成功");
                    } catch (Exception e) {
                        jsonObj.put("code", 1);
                         jsonObj.put("msg", "设置头像失败");;
                        LOG.e(e.toString());
                    }
               
            }
         }
         return jsonObj;
    }


**
     * 保存截图。
     * @param bufImg
     * @param imgType
     * @param tarPath
     * @throws Exception
     */
    public void save(String path,BufferedImage bufImg,int startX,int startY ,String imgName,String tarPath,int width,int height,String username,TuAccountAvatarMapper  avatarMpper,Map<String, String> reqParams) throws Exception{
        
        SftpFileOper sftpFileOper = new SftpFileOper();
        InputStream ins = null;
        FileMessage fileMessage = null;
        String filename = "";
        //截图
        subImg = bufImg.getSubimage(startX, startY, width, height);
        //保存截图
        //压缩图片为指定尺寸
        if(subImg.getWidth()!=width || subImg.getHeight()!=height){
            BufferedImage tempImg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
            tempImg.getGraphics().drawImage(subImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0,null);
            
            ins =  bufferedImagToInputStream(tempImg);//
            fileMessage = sftpFileOper.upSftpFileCommon(filename, ins, path);//完成数据提交上传到ftp服务器
        }else{
            fileMessage = sftpFileOper.upSftpFileCommon(filename, ins, path);//完成数据提交上传到ftp服务器
        }
        filename = fileMessage.getFileName();
        addUserHeadData( avatarMpper, path, filename,username,  reqParams);//向数据库插入数据
    }


public InputStream bufferedImagToInputStream(BufferedImage tempImg) throws IOException{
        ByteArrayOutputStream os = new ByteArrayOutputStream();  
        ImageIO.write(tempImg, "gif", os);  
        InputStream inputStrem = new ByteArrayInputStream(os.toByteArray());
        return inputStrem;
    }









0 0
原创粉丝点击