java实现图像缩略

来源:互联网 发布:网站建设用什么软件 编辑:程序博客网 时间:2024/04/27 22:30

 /**
    * 根据新输入的长宽生成图片缩略图
    * @param fileName
    * @param width
    * @param height
    * @return
    * @throws IOException
    */
    public static boolean setShrinkPhoto(String fileName, int width, int height)
            throws IOException {
        File file = new File(fileName); // 读入文件
        Image src = javax.imageio.ImageIO.read(file); // 构造Image对象
        int srcWidth = src.getWidth(null); // 得到源图宽
        int srcHeight = src.getHeight(null); // 得到源图长
        if (srcWidth > width || srcHeight > height) { // 如果文件本身较小则取消缩略图
            BufferedImage tag = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(src, 0, 0, width, height, null); // 绘制缩小后的图
            FileOutputStream out = new FileOutputStream(fileName); // 输出到文件流
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(tag); // 近JPEG编码
            out.close();
        }
        return true;
    }

    /**
    * 根据新输入的缩放比例生成图片缩略图
    * @param fileName
    * @param width
    * @param height
    * @return
    * @throws IOException
    */
    public static boolean setShrinkPhoto(String fileName, float width, float height)
            throws IOException {
        File file = new File(fileName); // 读入文件
        Image src = javax.imageio.ImageIO.read(file); // 构造Image对象
        int srcWidth = src.getWidth(null); // 得到源图宽
        int srcHeight = src.getHeight(null); // 得到源图长
        BufferedImage tag = new BufferedImage((int) (srcWidth * width),
                (int) (srcHeight * height), BufferedImage.TYPE_INT_RGB);
        tag.getGraphics().drawImage(src, 0, 0, (int) (srcWidth * width),
                (int) (srcHeight * height), null); // 绘制缩小后的图
        FileOutputStream out = new FileOutputStream(fileName); // 输出到文件流
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(tag); // 近JPEG编码
        out.close();
        return true;
    }