您当前的位置: 首页 > 

梁云亮

暂无认证

  • 2浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

不依赖第三方的 图片缩放工具类

梁云亮 发布时间:2021-06-26 20:38:26 ,浏览量:2

public class PicUtils {
    private static int width;
    private static int height;
    private static BufferedImage img;
    
    /**
     * 强制压缩、放大
     * @param destFile
     * @param w
     * @param h
     * @throws IOException
     */
    private static void resize(String destFile, int w, int h) throws IOException {
        BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        bufferedImage.getGraphics().fillRect(0, 0, w, h);
        bufferedImage.getGraphics().drawImage(img, 0, 0, w, h, null);//将原图片画到新图片上
        //输出新图片
        FileOutputStream out = new FileOutputStream(destFile);

        ImageIO.write(bufferedImage, destFile.substring(destFile.lastIndexOf('.') + 1), out);
        out.close();
    }
    
    /**
     * 按照固定的比例缩放图片
     * @param sourceFile  源图片
     * @param destFile 目标图片
     * @param scale 缩放比例
     * @throws IOException
     */
    public static void resize(String sourceFile, String destFile, double scale) throws IOException {
        img = ImageIO.read(new File(sourceFile));
        width = img.getWidth();
        height = img.getHeight();

        int w = (int) (width * scale);
        int h = (int) (height * scale);
        resize(destFile, w, h);
    }


    /**
     * 以高度为基准,等比例缩放图片
     * @param sourceFile 源图片
     * @param destFile 目标图片
     * @param h 作为基准的高度
     * @throws IOException
     */
    public static void resizeByHeight(String sourceFile, String destFile, int h) throws IOException {
        img = ImageIO.read(new File(sourceFile));
        width = img.getWidth();
        height = img.getHeight();
        int w = width * h / height;
        resize(destFile, w, h);
    }

    /**
     * 以宽度为基准,等比例缩放图片
     * @param sourceFile 源图片
     * @param destFile 目标图片
     * @param w 作为基准的宽度
     * @throws IOException
     */
    public static void resizeByWidth(String sourceFile, String destFile, int w) throws IOException {
        img = ImageIO.read(new File(sourceFile));
        width = img.getWidth();
        height = img.getHeight();
        int h = (height * w) / width;
        resize(destFile, w, h);
    }

    public static void main(String args[]) {
        try {
            String sourceFile = "e:\\1920X1050.jpg";
            resize(sourceFile, "e:/b1.jpg", 0.5);
            resizeByHeight(sourceFile,"e:/b2.jpg",200);
            resizeByWidth(sourceFile,"e:/b3.jpg",200);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0470s