java有关图片缩放的实现

目前有很多的图片缩放功能,我也借鉴很多的 资料完成来写这个代码,说实话 java 里面有个叫 BufferedImage 这个类,里面的方法 器就是解决图片的缩放功能不说废话直接上代码

/*
  * 图片缩放,w,h为缩放的目标宽度和高度
  * src为源文件目录,arcaddress为缩放后保存目录
  */
public static void zoomImage(String src,String arcaddress,int w,int h) throws Exception {
    double wr=0,hr=0;
    //获取文件
    File srcFile = new File(src);
    File destFile = new File(arcaddress);

    BufferedImage bufImg = ImageIO.read(srcFile); //读取图片
    /**
     * getScaledInstance(int width, int height, int hints)
     * 创建此图像的缩放版本。
     * */
    Image Itemp = bufImg.getScaledInstance(w, h, bufImg.SCALE_SMOOTH);//设置缩放目标图片模板

    wr=w*1.0/bufImg.getWidth();     //获取缩放比例
    hr=h*1.0 / bufImg.getHeight();

    /**
     * AffineTransformOp 类
     * 此类使用仿射转换来执行从源图像或 Raster 中 2D 坐标到目标图像或 Raster 中 2D 坐标的线性映射。
     * 所使用的插值类型由构造方法通过一个 RenderingHints 对象
     * 或通过此类中定义的整数插值类型之一来指定
     * */
    AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);
   /**
    * filter(BufferedImage src, BufferedImage dst)
    * 转换源 BufferedImage 并将结果存储在目标 BufferedImage 中。
    * */
    Itemp = ato.filter(bufImg, null);
    try {
        ImageIO.write((BufferedImage) Itemp,arcaddress.substring(arcaddress.lastIndexOf(".")+1), destFile); //写入缩减后的图片
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36423978/article/details/82379034