java图片压缩和剪裁示例

本文介绍了一个用于处理图片上传及缩放、裁剪等操作的Java实用类。该类能够根据指定尺寸调整图片大小,并支持多种图片格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 * Copyright 2013 NingPai, Inc. All rights reserved.
 * NINGPAI PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package co.dc.main.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 单个图片上传Util方法
 * @author zhangpeng
 */
public class UploadImage {
	
    /*
     *以下是图片缩放的方法 
     */
    
	public Image img; 
	public File donefile;
    public int width;  
    public int height;
	
    public UploadImage() {
        // TODO Auto-generated constructor stub
    }
    /**
     * 上传图片
     * @param uploadForm
     * @param request
     * @return imageurl
     */
        public String uploadImage(FileUploadForm uploadForm,
                HttpServletRequest request,MultipartFile mFile,String urlpath){
        // 存储图片路径
        String imageurl = "";
        if (mFile != null && mFile.getSize() != 0) {
            // 获取系统时间
            long now = System.currentTimeMillis();
            // 根据系统时间生成上传后保存的文件名
            String prefix = String.valueOf(now);
            // 保存图片路径
            String picPath = urlpath+"/";
            // 根据真实路径创建目录文件
//            File picSaveFile = new File(picPath);
//            if (!picSaveFile.exists()) {
//                picSaveFile.mkdirs();
//            }
            // 文件的后缀
            String fileNamess = picPath + prefix + ".jpg";
            imageurl = "photos/"+prefix;
            File file = new File(fileNamess);
            try {
                mFile.transferTo(file);
                donefile = new File(fileNamess);// 读入文件  
                img = ImageIO.read(donefile);      // 构造Image对象  
                width = img.getWidth(null);    // 得到源图宽  
                height = img.getHeight(null);  // 得到源图长 
                resizeFix(994, 830,picPath + prefix+"_1000.jpg");
                resizeFix2(2400, 1650,picPath + prefix+"_250.jpg");
            } catch (Exception e) {
            	e.printStackTrace();
            }
        }
        return imageurl+","+width+","+height;
        }
        
        /** 
         * 按照宽度还是高度进行【压缩】 
         * @param w int 最大宽度 
         * @param h int 最大高度 
         */  
        public void resizeFix(int w, int h,String newfileurl) throws IOException {
        	int h2 = 0,w2 = 0;
            if (width > w) {
            	h2 = (int)(height * w / width);
                if(h2 > h){
                	w2 = (int) (w * h / h2);
                	//System.out.println(w2+"=="+h);
                	resize1(w2, h,newfileurl);
                }else{
                	//System.out.println(w+"=="+h2);
                	resize1(w, h2,newfileurl);
                }
            }else if(height > h){
            	w2 = (int) (width * h / height);
            	//System.out.println(w2+"=="+h);
            	resize1(w2, h,newfileurl);
            }else{
            	//System.out.println(width+"=="+height);
            	resize1(width, height,newfileurl);
            }
        }  
        
        /** 
         * 按照宽度还是高度进行【裁剪 】
         * @param w int 最大宽度 
         * @param h int 最大高度 
         */  
        public void resizeFix2(int w, int h,String newfileurl) throws IOException {
            if (width > w && height > h) {
            	cutImage(donefile, new File(newfileurl), w, h);
            }else if(width > w && height <= h){
            	cutImage(donefile, new File(newfileurl), w, height);
            }else if(width <= w && height > h){
            	cutImage(donefile, new File(newfileurl), width, h);
            }else{
            	cutImage(donefile, new File(newfileurl), width, height);
            }
        }
        
        /** 
         * 强制压缩/放大图片到固定的大小 
         * @param w int 新宽度 
         * @param h int 新高度 
         */  
        public void resize1(int w, int h,String newfileurl) throws IOException {  
            // SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢  
            BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );   
            image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图  
            File destFile = new File(newfileurl);  
            FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流  
            // 可以正常实现bmp、png、gif转jpg
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
            encoder.encode(image); // JPEG编码  
            out.close(); 
        }
        
        /**
         * <p>Title: cutImage</p>
         * <p>Description:  根据原图与裁切size截取局部图片</p>
         * @param srcImg    源图片
         * @param output    图片输出流
         * @param rect        需要截取部分的坐标和大小
         */
        public void cutImage(File srcImg, File output,int w, int h){
        	java.awt.Rectangle rect = new java.awt.Rectangle(0, 0, w, h);
            if(srcImg.exists()){
                java.io.FileInputStream fis = null;
                ImageInputStream iis = null;
                try {
                    fis = new FileInputStream(srcImg);
                    // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
                    String types = Arrays.toString(ImageIO.getReaderFormatNames()).replace("]", ",");
                    String suffix = null;
                    // 获取图片后缀
                    if(srcImg.getName().indexOf(".") > -1) {
                        suffix = srcImg.getName().substring(srcImg.getName().lastIndexOf(".") + 1);
                    }// 类型和图片后缀全部小写,然后判断后缀是否合法
                    if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()+",") < 0){
                        return ;
                    }
                    // 将FileInputStream 转换为ImageInputStream
                    iis = ImageIO.createImageInputStream(fis);
                    // 根据图片类型获取该种类型的ImageReader
                    ImageReader reader = ImageIO.getImageReadersBySuffix(suffix).next();
                    reader.setInput(iis,true);
                    ImageReadParam param = reader.getDefaultReadParam();
                    param.setSourceRegion(rect);
                    BufferedImage bi = reader.read(0, param);
                    ImageIO.write(bi, suffix, output);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if(fis != null) fis.close();
                        if(iis != null) iis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }else {
            }
        }

//        public static void main(String[] args) {
//        	width = 1500;
//        	height = 1800;
//        	try {
//				resizeFix(241, 165, "");
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值