资讯专栏INFORMATION COLUMN

java对图片进行压缩和resize

dack / 3425人阅读

这里展示一下如何对图片进行压缩和resize。

压缩
public static boolean compress(String src,String to, float quality) {
        boolean rs = true;

        // Build param
        JPEGEncodeParam param = null;

        // Build encoder
        File destination = new File(to);
        FileOutputStream os = null;
        try {
            BufferedImage image = ImageIO.read(new File(src));
            param = JPEGCodec.getDefaultJPEGEncodeParam(image);
            param.setQuality(quality, false);

            os = FileUtils.openOutputStream(destination);
            JPEGImageEncoder encoder;
            if (param != null) {
                encoder = JPEGCodec.createJPEGEncoder(os, param);
            } else {
                return false;
            }
            encoder.encode(image);
        } catch(Exception e){
            e.printStackTrace();
            rs = false;
        }finally {
            IOUtils.closeQuietly(os);
        }
        return rs;
    }
resize
public static boolean resize(String src,String to,int newWidth,int newHeight) {
        try {
            File srcFile = new File(src);
            File toFile = new File(to);
            BufferedImage img = ImageIO.read(srcFile);
            int w = img.getWidth();
            int h = img.getHeight();
            BufferedImage dimg  = new BufferedImage(newWidth, newHeight, img.getType());
            Graphics2D g = dimg.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(img, 0, 0, newWidth, newHeight, 0, 0, w, h, null);
            g.dispose();
            ImageIO.write(dimg, "jpg", toFile);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/67503.html

相关文章

  • Android&Java面试题大全—金九银十面试必备

    摘要:需要校验字节信息是否符合规范,避免恶意信息和不规范数据危害运行安全。具有相同哈希值的键值对会组成链表。通过在协议下添加了一层协议对数据进行加密从而保证了安全。常见的非对称加密包括等。 类加载过程 Java 中类加载分为 3 个步骤:加载、链接、初始化。 加载。 加载是将字节码数据从不同的数据源读取到JVM内存,并映射为 JVM 认可的数据结构,也就是 Class 对象的过程。数据源可...

    renweihub 评论0 收藏0
  • 图像处理 - ImageMagick 简单介绍与案例

    摘要:是一款创建编辑合成,转换图像的命令行工具。上面两条三次贝塞尔曲线的坐标分别表示起始点,起始点的控制点,结束点的控制点,结束点。 在客户端我们可以用 PhotoShop 等 GUI 工具处理静态图片或者动态 GIF 图片,不过在服务器端对于 WEB 应用程序要处理图片格式转换,缩放裁剪,翻转扭曲,PDF解析等操作, GUI 软件就很难下手了,所以此处需要召唤命令行工具来帮我们完成这些事。...

    youkede 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<