82-java上传图片 并压缩


    private BufferedImage getNewImage(MultipartFile oldImage, double width, double height) throws IOException{
        /*srcURl 原图地址;deskURL 缩略图地址;comBase 压缩基数;scale 压缩限制(宽/高)比例*/

        ByteArrayInputStream bais = new ByteArrayInputStream(oldImage.getBytes());
        MemoryCacheImageInputStream mciis = new MemoryCacheImageInputStream(bais);
        Image src = ImageIO.read(mciis);
        double srcHeight = src.getHeight(null);
        double srcWidth = src.getWidth(null);
        double deskHeight = 0;//缩略图高
        double deskWidth  = 0;//缩略图宽
        if (srcWidth>srcHeight) {

            if (srcWidth>width) {
                if (width/height>srcWidth/srcHeight) {
                    deskHeight = height;
                    deskWidth = srcWidth/(srcHeight/height);
                }
                else {
                    deskHeight = width/(srcWidth/srcHeight);
                    deskWidth = width;
                }
            }
            else {

                if (srcHeight>height) {
                    deskHeight = height;
                    deskWidth = srcWidth/(srcHeight/height);
                }else {
                    deskHeight=srcHeight;
                    deskWidth=srcWidth;
                }

            }

        }
        else if(srcHeight>srcWidth)
        {
            if (srcHeight>(height)) {
                if ((height)/width>srcHeight/srcWidth) {
                    deskHeight = srcHeight/(srcWidth/width);
                    deskWidth = width;
                }else {
                    deskHeight = height;
                    deskWidth = (height)/(srcHeight/srcWidth);
                }
            }
            else {
                if (srcWidth>width) {
                    deskHeight = srcHeight/(srcWidth/width);
                    deskWidth = width;
                }else {
                    deskHeight=srcHeight;
                    deskWidth=srcWidth;
                }

            }

        }
        else if (srcWidth==srcHeight) {

            if (width>=(height)&&srcHeight>(height)) {
                deskWidth=(height);
                deskHeight=(height);
            }
            else if (width<=(height)&&srcWidth>width) {
                deskWidth=width;
                deskHeight=width;
            }
            else  if (width==(height)&&srcWidth

上传的MultipartFile

@RequestParam("picFile") MultipartFile file
String originalName = file.getOriginalFilename();
originalName = originalName.toLowerCase();
resp.setType(FilenameUtils.getExtension(originalName));

String id = DateUtils.format(new Date(),"yyyyMMddHHmmssSSS");

resp.setFileName(id + "." + resp.getType());

File path = FileUtils.getFile(imageRootDir);

FileUtils.forceMkdir(path);

File ordinalFile = FileUtils.getFile(path,resp.getFileName());

ImageIO.write(newImage, resp.getType(), ordinalFile);

你可能感兴趣的:(java)