java图片压缩

使用java对图片进行缩放,

pom依赖

        <!-- 照片处理 -->
        <dependency>
            <groupId>com.mortennobel</groupId>
            <artifactId>java-image-scaling</artifactId>
            <version>0.8.6</version>
        </dependency>


java范例代码

package com.mypackage;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import com.mortennobel.imagescaling.DimensionConstrain;
import com.mortennobel.imagescaling.ResampleOp;


public class ImageUtil {

    /**
     * 默认缩放比例
     */
    public final static int SCALE = 10;

    /**
     * 默认缩放后图片宽度   
     */
    //public final static int WIDTH = ApplicationConfig.getInstance().getThumbnailWidth();
    public final static int WIDTH = 100;

    /**
     * 默认缩放后图片高度
     */
    //public final static int HEIGHT = ApplicationConfig.getInstance().getThumbnailHeight();
    public final static int HEIGHT = 100;

    /**
     * gif
     */
    public final static String GIF = "gif";

    /**
     * png
     */
    public final static String PNG = "png";


    public static byte[] getImageByUrl(URI uri) {
        File file = new File(uri);
        if (file.exists() && file.isFile()) {
            return file2byte(file);
        }
        return null;
    }

    public static byte[] getImageByPath(String path) {
        File file = new File(path);
        if (file.exists() && file.isFile()) {
            return file2byte(file);
        }
        return null;
    }

    // public static saveImage
    public static byte[] file2byte(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 按默认比例缩放图片。
     *
     * @param src 源图片文件流
     * @param fileSuffix 后缀名
     * @return 缩略图文件流
     */
    public static InputStream getThumbnailByDefaultScale(InputStream src,
            String fileSuffix) throws Exception {

        return getThumbnailByScale(src, fileSuffix, SCALE);

    }

    /**
     * 按比例缩放图片。
     *
     * @param src 源图片文件流
     * @param fileSuffix 后缀名
     * @param scale 图片缩放比例
     * @return 缩略图文件流
     */
    public static InputStream getThumbnailByScale(InputStream src,
            String fileSuffix, int scale) throws Exception {

        if(GIF.equals(fileSuffix.toLowerCase())) {
            return src;
        }
        InputStream is = null;
        try {
            BufferedImage image = ImageIO.read(src);
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            int w = width / scale;
            int h = height / scale;

            ResampleOp rsop = new ResampleOp(DimensionConstrain.createMaxDimension(w, h, true));
            BufferedImage to = rsop.filter(image, null);

            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(to, fileSuffix, imOut);

            is = new ByteArrayInputStream(bs.toByteArray());
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return is;
    }

    /**
     * 按默认宽度高度缩放。
     *
     * @param src 源图片文件流
     * @param fileSuffix 后缀名
     * @return 缩略图文件流
     */
    public static InputStream getThumbnail(InputStream src,
            String fileSuffix) throws Exception {

        return compressImage(src, fileSuffix, WIDTH, HEIGHT);

    }
    
    /**
     * 指定宽度高度缩放。<br>
     * 图片的实际宽高不足时返回null
     * @param src 源图片文件流
     * @param fileSuffix 后缀名
     * @param _width 缩略图宽度
     * @param _height 缩略图高度
     * @return 缩略图文件流
     */
    public static InputStream getThumbnail(InputStream src,
            String fileSuffix, int _width, int _height) throws Exception {

        if(GIF.equals(fileSuffix.toLowerCase())) {
            return src;
        }
        InputStream is = null;
        try {
            BufferedImage bi2 = ImageIO.read(src);
            //原图宽高
            int width = bi2.getWidth(null);
            int height = bi2.getHeight(null);
            if(width < _width || height < _height){
                return null;
            }
            //缩放后宽高
            int newWidth = 0;
            int newHeight = 0;
            if(width <= _width && height <= _height) {
                _width = width;
                _height = height;
            }
            //计算按原图的横向纵向最大比例方向缩放
            //横向图片的场合
            if (width / _width > height / _height) {
                newWidth = _width;
                newHeight = _width * height / width;
            } else {
                newHeight = _height;
                newWidth = _height * width / height;
            }

            ResampleOp rsop = new ResampleOp(DimensionConstrain.createMaxDimension(newWidth, newHeight, true));
            BufferedImage to = rsop.filter(bi2, null);

            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(to, fileSuffix, imOut);

            is = new ByteArrayInputStream(bs.toByteArray());

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        } finally{
            //关于原来的流
            if(src != null){
                src.close();
            }
        }
        return is;

    }

    /**
     * 根据原图压缩为系统允许的最大的尺寸的图片。
     *
     * @param src 源图片文件流
     * @param fileSuffix 后缀名
     * @return 缩略图文件流
     */
    public static InputStream compressMaxImage(InputStream src,
            String fileSuffix, int maxWidth) throws Exception {

        return compressImage(src, fileSuffix, maxWidth);

    }

    /**
     * 固定图片宽高缩放(按原图的横向纵向最大比例方向缩放)。
     *
     * @param src 源图片文件流
     * @param fileSuffix 后缀名
     * @param _width 缩略图宽度
     * @return 缩略图文件流
     */
    public static InputStream compressImage(InputStream src,
            String fileSuffix, int _width, int _height) throws Exception {

        if(GIF.equals(fileSuffix.toLowerCase())) {
            return src;
        }
        InputStream is = null;
        try {
            BufferedImage bi2 = ImageIO.read(src);
            //原图宽高
            int width = bi2.getWidth(null);
            int height = bi2.getHeight(null);
            //缩放后宽高
            int newWidth = 0;
            int newHeight = 0;
            if(width <= _width && height <= _height) {
                _width = width;
                _height = height;
            }
            //计算按原图的横向纵向最大比例方向缩放
            //横向图片的场合
            if (width / _width > height / _height) {
                newWidth = _width;
                newHeight = _width * height / width;
            } else {
                newHeight = _height;
                newWidth = _height * width / height;
            }

            ResampleOp rsop = new ResampleOp(DimensionConstrain.createMaxDimension(newWidth, newHeight, true));
            BufferedImage to = rsop.filter(bi2, null);

            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(to, fileSuffix, imOut);

            is = new ByteArrayInputStream(bs.toByteArray());
            //关于原来的流
            if(src != null){
                src.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return is;

    }

    /**
     * 固定图片宽度缩放。
     *
     * @param src 源图片文件流
     * @param fileSuffix 后缀名
     * @param _width 缩略图宽度
     * @return 缩略图文件流
     */
    public static InputStream compressImage(InputStream src,
            String fileSuffix, int _width) throws Exception {

        if(GIF.equals(fileSuffix.toLowerCase())) {
            return src;
        }
        InputStream is = null;
        try {
            BufferedImage bi2 = ImageIO.read(src);
            //原图宽高
            int width = bi2.getWidth(null);
            int height = bi2.getHeight(null);
            //缩放后宽高
            int newWidth = 0;
            int newHeight = 0;
            if(width < _width) {
                _width = width;
            }
            newWidth = _width;
            //计算按原图的横向纵向最大比例方向缩放
            //横向图片的场合
            newHeight = height * _width / width;

            ResampleOp rsop = new ResampleOp(DimensionConstrain.createMaxDimension(newWidth, newHeight, true));
            BufferedImage to = rsop.filter(bi2, null);

            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(to, fileSuffix, imOut);

            is = new ByteArrayInputStream(bs.toByteArray());
            //关于原来的流
            if(src != null){
                src.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return is;

    }

}

 

Java 中可以使用 ImageIO 类和 BufferedImage 类来进行图片压缩操作。以下是一个简单的示例代码: ```java import java.awt.Dimension; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class ImageCompressor { public static void main(String[] args) throws IOException { File inputFile = new File("input.jpg"); BufferedImage inputImage = ImageIO.read(inputFile); int maxWidth = 800; int maxHeight = 600; Dimension newDimension = getScaledDimension(new Dimension(inputImage.getWidth(), inputImage.getHeight()), new Dimension(maxWidth, maxHeight)); BufferedImage outputImage = new BufferedImage(newDimension.width, newDimension.height, BufferedImage.TYPE_INT_RGB); outputImage.getGraphics().drawImage(inputImage.getScaledInstance(newDimension.width, newDimension.height, Image.SCALE_SMOOTH), 0, 0, null); File outputFile = new File("output.jpg"); ImageIO.write(outputImage, "jpg", outputFile); } public static Dimension getScaledDimension(Dimension imageSize, Dimension boundary) { int width = imageSize.width; int height = imageSize.height; int maxWidth = boundary.width; int maxHeight = boundary.height; double ratio = Math.min((double) maxWidth / width, (double) maxHeight / height); return new Dimension((int) (width * ratio), (int) (height * ratio)); } } ``` 上述代码中,首先读取一张图片(假设为 input.jpg),然后指定最大宽度和最大高度进行压缩。使用 `getScaledDimension` 方法计算新的宽度和高度,然后创建一个新的 `BufferedImage` 对象并将原始图片缩放到新的尺寸,最后将新的图片保存到文件中(假设为 output.jpg)。 需要注意的是,这里使用的是 `Image.SCALE_SMOOTH` 参数,表示使用平滑缩放算法,可以得到更好的压缩效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值