java 图片的自定义大小

java 小功能,进行图片的自定义大小

package com.project.video.controller;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

public class ImageOp {
    
     public static String DEFAULT_PREVFIX = "thumb_";
     public static Boolean DEFAULT_FORCE = false;//建议该值为false
     private static  Logger loger = Logger.getLogger(ImageOp.class);
     /**
      * <p>Title: thumbnailImage</p>
      * @param imagePath 原图片路径
      * @param w   缩略图宽
      * @param h   缩略图高
      * @param prevfix 生成缩略图的前缀
      * @param force  是否强制按照宽高生成缩略图(如果为false,则生成最佳比例缩略图)
      */
     public  static void thumbnailImage(MultipartFile imagePath, int w, int h, String prevfix, boolean force){
      //File imgFile = new File(imagePath);
         
         
       try {
           loger.info("start .......");
           
        // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
        String types = Arrays.toString(ImageIO.getReaderFormatNames());
        String suffix = null;
        // 获取图片后缀
        loger.info("图片名称"+imagePath.getOriginalFilename());
        if(imagePath.getOriginalFilename().indexOf(".") > -1) {
            
         suffix = imagePath.getOriginalFilename().substring(imagePath.getOriginalFilename().lastIndexOf(".") + 1);
        }// 类型和图片后缀全部小写,然后判断后缀是否合法
        if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()) < 0){
            loger.error("图片后缀不合法");
         return ;
        }
        //获取原图的输入流
        BufferedImage img = ImageIO.read(imagePath.getInputStream());
        if(!force){
         // 根据原图与要求的缩略图比例,找到最合适的缩略图比例
         int width = img.getWidth(null);
         int height = img.getHeight(null);
         if((width*1.0)/w < (height*1.0)/h){
          if(width > w){
           h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w/(width*1.0)));
           
          }
         } else {
          if(height > h){
           w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h/(height*1.0)));
          
          }
         }
        }
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.getGraphics();
        g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
        g.dispose();
        loger.info("图片生成");
        String desc ="f:\12345.jpg";
        // 将图片保存在原目录并加上前缀
        ImageIO.write(bi, suffix, new File(desc));
       
       } catch (Exception e) {
           
          e.printStackTrace();
          loger.error("图片生成错误");
      
       }
      
     }
    
    }
    
原创打造,多多指教
原文地址:https://www.cnblogs.com/iscys/p/9514354.html