ImageWriterCompressionTest.java revision 13608:6648f64ba30a
1/*
2 * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24import java.awt.Color;
25import java.awt.Font;
26import java.awt.Graphics2D;
27import java.awt.RenderingHints;
28import java.awt.geom.Rectangle2D;
29import java.awt.image.BufferedImage;
30import java.io.File;
31import java.io.FileOutputStream;
32import java.io.IOException;
33import java.util.Arrays;
34import java.util.HashSet;
35import java.util.Iterator;
36import java.util.Locale;
37import java.util.Set;
38import javax.imageio.IIOImage;
39import javax.imageio.ImageIO;
40import javax.imageio.ImageWriteParam;
41import javax.imageio.ImageWriter;
42import javax.imageio.stream.ImageOutputStream;
43
44/**
45 * @test @bug 6488522
46 * @summary Check the compression support in imageio ImageWriters
47 * @run main ImageWriterCompressionTest
48 */
49public class ImageWriterCompressionTest {
50
51    // ignore jpg (fail):
52    // Caused by: javax.imageio.IIOException: Invalid argument to native writeImage
53    private static final Set<String> IGNORE_FILE_SUFFIXES
54        = new HashSet<String>(Arrays.asList(new String[] {
55            "bmp", "gif",
56            "jpg", "jpeg",
57//            "tif", "tiff"
58        } ));
59
60    public static void main(String[] args) {
61        Locale.setDefault(Locale.US);
62
63        final BufferedImage image
64            = new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);
65
66        final Graphics2D g2d = image.createGraphics();
67        try {
68            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
69                                 RenderingHints.VALUE_ANTIALIAS_ON);
70            g2d.setRenderingHint(RenderingHints.KEY_RENDERING,
71                                 RenderingHints.VALUE_RENDER_QUALITY);
72            g2d.scale(2.0, 2.0);
73
74            g2d.setColor(Color.red);
75            g2d.draw(new Rectangle2D.Float(10, 10, 100, 100));
76            g2d.setColor(Color.blue);
77            g2d.fill(new Rectangle2D.Float(12, 12, 98, 98));
78            g2d.setColor(Color.green);
79            g2d.setFont(new Font(Font.SERIF, Font.BOLD, 14));
80
81            for (int i = 0; i < 15; i++) {
82                g2d.drawString("Testing Compression ...", 20, 20 + i * 16);
83            }
84
85            final String[] fileSuffixes = ImageIO.getWriterFileSuffixes();
86
87            final Set<String> testedWriterClasses = new HashSet<String>();
88
89            for (String suffix : fileSuffixes) {
90
91                if (!IGNORE_FILE_SUFFIXES.contains(suffix)) {
92                    final Iterator<ImageWriter> itWriters
93                        = ImageIO.getImageWritersBySuffix(suffix);
94
95                    final ImageWriter writer;
96                    final ImageWriteParam writerParams;
97
98                    if (itWriters.hasNext()) {
99                        writer = itWriters.next();
100
101                        if (testedWriterClasses.add(writer.getClass().getName())) {
102                            writerParams = writer.getDefaultWriteParam();
103
104                            if (writerParams.canWriteCompressed()) {
105                                testCompression(image, writer, writerParams, suffix);
106                            }
107                        }
108                    } else {
109                        throw new RuntimeException("Unable to get writer !");
110                    }
111                }
112            }
113        } catch (IOException ioe) {
114            throw new RuntimeException("IO failure", ioe);
115        }
116        finally {
117            g2d.dispose();
118        }
119    }
120
121    private static void testCompression(final BufferedImage image,
122                                        final ImageWriter writer,
123                                        final ImageWriteParam writerParams,
124                                        final String suffix)
125        throws IOException
126    {
127        System.out.println("Compression types: "
128            + Arrays.toString(writerParams.getCompressionTypes()));
129
130        // Test Compression modes:
131        try {
132            writerParams.setCompressionMode(ImageWriteParam.MODE_DISABLED);
133            saveImage(image, writer, writerParams, "disabled", suffix);
134        } catch (Exception e) {
135            System.out.println("CompressionMode Disabled not supported: "+ e.getMessage());
136        }
137
138        try {
139            writerParams.setCompressionMode(ImageWriteParam.MODE_DEFAULT);
140            saveImage(image, writer, writerParams, "default", suffix);
141        } catch (Exception e) {
142            System.out.println("CompressionMode Default not supported: "+ e.getMessage());
143        }
144
145        writerParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
146        writerParams.setCompressionType(selectCompressionType(suffix,
147                        writerParams.getCompressionTypes()));
148
149        System.out.println("Selected Compression type: "
150            + writerParams.getCompressionType());
151
152        long prev = Long.MAX_VALUE;
153        for (int i = 10; i >= 0; i--) {
154            float quality = 0.1f * i;
155            writerParams.setCompressionQuality(quality);
156
157            long len = saveImage(image, writer, writerParams,
158                                 String.format("explicit-%.1f", quality), suffix);
159
160            if (len <= 0) {
161                throw new RuntimeException("zero file length !");
162            } else if (len > prev) {
163                throw new RuntimeException("Incorrect file length: " + len
164                    + " larger than previous: " + prev + " !");
165            }
166            prev = len;
167        }
168    }
169
170    private static String selectCompressionType(final String suffix,
171                                                final String[] types)
172    {
173        switch (suffix) {
174            case "tif":
175            case "tiff":
176                return "LZW";
177            default:
178                return types[0];
179        }
180    }
181
182    private static long saveImage(final BufferedImage image,
183                                  final ImageWriter writer,
184                                  final ImageWriteParam writerParams,
185                                  final String mode,
186                                  final String suffix) throws IOException
187    {
188        final File imgFile = new File("WriterCompressionTest-"
189                                      + mode + '.' + suffix);
190        System.out.println("Writing file: " + imgFile.getAbsolutePath());
191
192        final ImageOutputStream imgOutStream
193            = ImageIO.createImageOutputStream(new FileOutputStream(imgFile));
194        try {
195            writer.setOutput(imgOutStream);
196            writer.write(null, new IIOImage(image, null, null), writerParams);
197        } finally {
198            imgOutStream.close();
199        }
200        return imgFile.length();
201    }
202}
203