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;
    }
    }

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

  • 相关阅读:
    ASP.NET异步处理
    C# TPL学习
    canvas 动画库 CreateJs 之 EaselJS(上篇)
    kafka消息的可靠性
    流式处理框架storm浅析(下篇)
    流式处理框架storm浅析(上篇)
    网易严选后台系统前端规范化解决方案
    Question | 移动端虚拟机注册等作弊行为的破解之道
    Puppeteer入门初探
    ThreeJs 3D 全景项目开发总结
  • 原文地址:https://www.cnblogs.com/nankeyimengningchenlun/p/11720030.html
Copyright © 2011-2022 走看看