zoukankan      html  css  js  c++  java
  • tif图片压缩

    tif图片在ImageIo.read获取时,返回为空,导致无法使用,百度了很久,很多人说jai可以,便去看了下,总结如下:

    public static void CompressPic(String srcPath, long maxSize) throws Exception {
    double cutPercent = 0.1;
    File file = new File(srcPath);
    //读取tif图
    SeekableStream s = new FileSeekableStream(srcPath);
    TIFFDecodeParam tifParam = new TIFFDecodeParam();
    ImageDecoder dec = ImageCodec.createImageDecoder("TIFF", s, tifParam);
    RenderedImage renderedImage = dec.decodeAsRenderedImage(); // 图片解码
    //转为bufferedImage对象
    BufferedImage bufferedImage = ImageUtil.convertRenderedImage(renderedImage);
    int width = bufferedImage.getWidth(null);
    int height = bufferedImage.getHeight(null);
    long fileLength = file.length();
    while ((fileLength / 1024) >= maxSize) {
    width = (int) (width * (1 - cutPercent));
    height = (int) (height * (1 - cutPercent));
    BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
    tag.getGraphics().drawImage(bufferedImage, 0, 0, width, height, null); // 绘制缩小后的图
    FileOutputStream deskImage = new FileOutputStream(srcPath); // 输出到文件流
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(deskImage);
    encoder.encode(tag); // 近JPEG编码
    deskImage.close();

    File file1 = new File(srcPath);
    BufferedImage bufferedImage1 = ImageIO.read(new FileInputStream(file1));
    width = bufferedImage1.getWidth(null);
    height = bufferedImage1.getHeight(null);
    fileLength = file1.length();
    }
    }

    ===============================

    这是tif的renderedImage对象转为Image对象的方法

    public class ImageUtil {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static BufferedImage convertRenderedImage(RenderedImage img) {
    if (img instanceof BufferedImage) {
    return (BufferedImage) img;
    }
    ColorModel cm = img.getColorModel();
    int width = img.getWidth();
    int height = img.getHeight();
    WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
    boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
    Hashtable properties = new Hashtable();
    String[] keys = img.getPropertyNames();
    if (keys != null) {
    for (int i = 0; i < keys.length; i++) {
    properties.put(keys[i], img.getProperty(keys[i]));
    }
    }
    BufferedImage result = new BufferedImage(cm, raster, isAlphaPremultiplied, properties);
    img.copyData(raster);
    return result;
    }
    }

    希望未来的自己更加努力!

  • 相关阅读:
    [转] Linux 最大进程数, unable to create new native thread问题
    [转] Maven 从命令行获取项目的版本号
    [转]【JVM】调优笔记2-----JVM在JDK1.8以后的新特性以及VisualVM的安装使用
    DISCUZ 自定义模板
    Linux系统性能统计工具Sar和实时系统性能监控脚本
    shell脚本常规技巧
    Java中文编码小结
    json-smart 使用示例(推荐fastjson)
    HBase Java简单示例
    Ehcache BigMemory: 摆脱GC困扰
  • 原文地址:https://www.cnblogs.com/nankeyimengningchenlun/p/11720030.html
Copyright © 2011-2022 走看看