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

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

  • 相关阅读:
    block的使用
    控制器的多种创建方式
    指针函数和函数指针
    UIScrollView实现图片轮播器及其无限循环效果
    如何按顺序执行两个动画
    代理、通知、KVO的应用
    CAlayer层的属性
    UIView的autoresizingMask和autoresizesSubviews属性的剖析
    面向对象编程思想(OOP)总结
    scala中闭包的使用
  • 原文地址:https://www.cnblogs.com/nankeyimengningchenlun/p/11720030.html
Copyright © 2020-2023  润新知