博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java 文件生成缩略图方法一
阅读量:7007 次
发布时间:2019-06-27

本文共 1788 字,大约阅读时间需要 5 分钟。

hot3.png

public static void createThumbnail(String filename, int thumbWidth,
            int thumbHeight, int quality, String outFilename)
            throws InterruptedException, FileNotFoundException, IOException {
        // load image from filename
        Image image = Toolkit.getDefaultToolkit().getImage(filename);
        MediaTracker mediaTracker = new MediaTracker(new Container());
        mediaTracker.addImage(image, 0);
        mediaTracker.waitForID(0);
        // use this to test for errors at this point:
        // System.out.println(mediaTracker.isErrorAny());
        // determine thumbnail size from WIDTH and HEIGHT
        double thumbRatio = (double) thumbWidth / (double) thumbHeight;
        int imageWidth = image.getWidth(null);
        int imageHeight = image.getHeight(null);
        double imageRatio = (double) imageWidth / (double) imageHeight;
        if (thumbRatio < imageRatio) {
            thumbHeight = (int) (thumbWidth / imageRatio);
        } else {
            thumbWidth = (int) (thumbHeight * imageRatio);
        }
        // draw original image to thumbnail image object and
        // scale it to the new size on-the-fly
        BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
        // save thumbnail image to outFilename
        BufferedOutputStream out = new BufferedOutputStream(
                new FileOutputStream(outFilename));
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
        quality = Math.max(0, Math.min(quality, 100));
        param.setQuality((float) quality / 100.0f, false);
        encoder.setJPEGEncodeParam(param);
        encoder.encode(thumbImage);
        out.close();
    }

转载于:https://my.oschina.net/u/238082/blog/144893

你可能感兴趣的文章
Wpf Binding.Path设置
查看>>
jfinal控制器添加多个拦截器
查看>>
跟着百度学PHP[14]-初识PDO数据库抽象层
查看>>
小豆包的学习之旅:机器人定位
查看>>
好程序猿训练营,让你成为名副事实上的好程序猿
查看>>
有关一道printf 的面试题
查看>>
#AOS应用基础平台# 实现了在用户权限范围内自己定义的快捷菜单的导航展示
查看>>
[转]ssh中如何实现定时任务(spring对quartz的支持)
查看>>
mysql查询表的字符集
查看>>
读研以来的一些感想:名校好在哪里?
查看>>
大数据中心的业务研发路线
查看>>
rtmp推流开源代码备注一下
查看>>
SQLServer 日期函数大全 SQLServer 时间函数大全
查看>>
program与module
查看>>
软件架构师应该知道的97件事
查看>>
jquery操作"元素属性"
查看>>
用Python写一个本地Sogou代理服务器程序
查看>>
ASP.NET内置票据认证
查看>>
大话GC菜鸟系列
查看>>
C# WinForm TextBox猜想输入和历史记录输入(源码)
查看>>