Java Code Examples for javax.imageio.ImageIO#createImageOutputStream()

The following examples show how to use javax.imageio.ImageIO#createImageOutputStream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ScreenCapture.java    From logbook-kai with MIT License 6 votes vote down vote up
/**
 * BufferedImageをJPEG形式にエンコードします
 *
 * @param image BufferedImage
 * @return JPEG形式の画像
 * @throws IOException 入出力例外
 */
static byte[] encodeJpeg(BufferedImage image) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try (ImageOutputStream ios = ImageIO.createImageOutputStream(out)) {
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
        try {
            ImageWriteParam iwp = writer.getDefaultWriteParam();
            if (iwp.canWriteCompressed()) {
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality(QUALITY);
            }
            writer.setOutput(ios);
            writer.write(null, new IIOImage(image, null, null), iwp);
        } finally {
            writer.dispose();
        }
    }
    return out.toByteArray();
}
 
Example 2
Source File: LUTCompareTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 3
Source File: EmbeddedFormatTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void doTest(String compression, int bi_type) throws IOException {
    System.out.println("Test " + compression + " on " + getImageTypeName(bi_type));
    BufferedImage src = createTestImage(bi_type);
    writer.reset();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageOutputStream ios =
            ImageIO.createImageOutputStream(baos);
    writer.setOutput(ios);

    ImageWriteParam wparam = prepareWriteParam(compression);
    writer.write(null, new IIOImage(src, null, null), wparam);
    ios.flush();
    ios.close();

    // read result
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ImageInputStream iis = ImageIO.createImageInputStream(bais);
    reader.reset();
    reader.setInput(iis);

    BufferedImage dst = reader.read(0);

    checkResult(dst);
}
 
Example 4
Source File: WriteProgressListenerTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void doTest() {
    try {
        System.out.println("Progress test for " + compression_type);
        BufferedImage bi = new BufferedImage(20, 300, BufferedImage.TYPE_INT_RGB);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(baos);

        Iterator iter = ImageIO.getImageWritersByFormatName(format);
        if (!iter.hasNext()) {
            throw new RuntimeException("No available writer for " + format);
        }
        ImageWriter writer = (ImageWriter)iter.next();

        writer.setOutput(ios);
        writer.addIIOWriteProgressListener(listener);

        IIOImage iio_img = new IIOImage(bi, null, null);

        ImageWriteParam param = writer.getDefaultWriteParam();

        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionType(compression_type);


        writer.write(null, iio_img, param);

        if (!listener.isTestPassed) {
            throw new RuntimeException("Test for " + compression_type + " does not finish correctly!");
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Source File: ImageIOHelper.java    From tess4j with Apache License 2.0 5 votes vote down vote up
public static List<File> createTiffFiles(List<IIOImage> imageList, int index, int dpiX, int dpiY) throws IOException {
    List<File> tiffFiles = new ArrayList<File>();

    //Set up the writeParam
    TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    //Get tiff writer and set output to file
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
    if (!writers.hasNext()) {
        throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE);
    }
    ImageWriter writer = writers.next();

    //Get the stream metadata
    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

    // all if index == -1; otherwise, only index-th
    for (IIOImage oimage : (index == -1 ? imageList : imageList.subList(index, index + 1))) {
        if (dpiX != 0 && dpiY != 0) {
            // Get the default image metadata.
            ImageTypeSpecifier imageType = ImageTypeSpecifier.createFromRenderedImage(oimage.getRenderedImage());
            ImageWriteParam param = writer.getDefaultWriteParam();
            IIOMetadata imageMetadata = writer.getDefaultImageMetadata(imageType, param);
            imageMetadata = setDPIViaAPI(imageMetadata, dpiX, dpiY);
            oimage.setMetadata(imageMetadata);
        }

        File tiffFile = File.createTempFile(OUTPUT_FILE_NAME, TIFF_EXT);
        try (ImageOutputStream ios = ImageIO.createImageOutputStream(tiffFile)) {
            writer.setOutput(ios);
            writer.write(streamMetadata, oimage, tiffWriteParam);
            tiffFiles.add(tiffFile);
        }
    }
    writer.dispose();

    return tiffFiles;
}
 
Example 6
Source File: TopDownTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static void writeWithCompression(BufferedImage src,
                                         String compression) throws IOException
{
    System.out.println("Compression: " + compression);
    ImageWriter writer = ImageIO.getImageWritersByFormatName("BMP").next();
    if (writer == null) {
        throw new RuntimeException("Test failed: no bmp writer available");
    }
    File fout = File.createTempFile(compression + "_", ".bmp",
                                    new File("."));

    ImageOutputStream ios = ImageIO.createImageOutputStream(fout);
    writer.setOutput(ios);

    BMPImageWriteParam param = (BMPImageWriteParam)
            writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionType(compression);
    param.setTopDown(true);
    writer.write(null, new IIOImage(src, null, null), param);
    writer.dispose();
    ios.flush();
    ios.close();

    BufferedImage dst = ImageIO.read(fout);

    verify(dst);
}
 
Example 7
Source File: RuntimeBuiltinLeafInfoImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public Base64Data print(Image v) {
    ByteArrayOutputStreamEx imageData = new ByteArrayOutputStreamEx();
    XMLSerializer xs = XMLSerializer.getInstance();

    String mimeType = xs.getXMIMEContentType();
    if(mimeType==null || mimeType.startsWith("image/*"))
        // because PNG is lossless, it's a good default
        //
        // mime type can be a range, in which case we can't just pass that
        // to ImageIO.getImageWritersByMIMEType, so here I'm just assuming
        // the default of PNG. Not sure if this is complete.
        mimeType = "image/png";

    try {
        Iterator<ImageWriter> itr = ImageIO.getImageWritersByMIMEType(mimeType);
        if(itr.hasNext()) {
            ImageWriter w = itr.next();
            ImageOutputStream os = ImageIO.createImageOutputStream(imageData);
            w.setOutput(os);
            w.write(convertToBufferedImage(v));
            os.close();
            w.dispose();
        } else {
            // no encoder
            xs.handleEvent(new ValidationEventImpl(
                ValidationEvent.ERROR,
                Messages.NO_IMAGE_WRITER.format(mimeType),
                xs.getCurrentLocation(null) ));
            // TODO: proper error reporting
            throw new RuntimeException("no encoder for MIME type "+mimeType);
        }
    } catch (IOException e) {
        xs.handleError(e);
        // TODO: proper error reporting
        throw new RuntimeException(e);
    }
    Base64Data bd = new Base64Data();
    imageData.set(bd,mimeType);
    return bd;
}
 
Example 8
Source File: MergeTreeTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    ImageWriter iw =
        (ImageWriter)ImageIO.getImageWritersByFormatName("jpeg").next();

    ImageTypeSpecifier type =
        ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);

    ImageOutputStream ios =
        ImageIO.createImageOutputStream(new File("MergeTreeTest.jpeg"));
    iw.setOutput(ios);

    IIOMetadata meta = iw.getDefaultImageMetadata(type, null);

    boolean isFailed = false;

    String[] fmts = meta.getMetadataFormatNames();
    for (int i=0; i<fmts.length; i++) {
        System.out.print("Format: " + fmts[i] + " ... ");
        Node root = meta.getAsTree(fmts[i]);
        try {
            meta.mergeTree(fmts[i], root);
        } catch (NullPointerException e) {
            throw new RuntimeException("Test failed for format " + fmts[i], e);
        }
        System.out.println("PASSED");
    }
}
 
Example 9
Source File: TopDownTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static void writeWithCompression(BufferedImage src,
                                         String compression) throws IOException
{
    System.out.println("Compression: " + compression);
    ImageWriter writer = ImageIO.getImageWritersByFormatName("BMP").next();
    if (writer == null) {
        throw new RuntimeException("Test failed: no bmp writer available");
    }
    File fout = File.createTempFile(compression + "_", ".bmp",
                                    new File("."));

    ImageOutputStream ios = ImageIO.createImageOutputStream(fout);
    writer.setOutput(ios);

    BMPImageWriteParam param = (BMPImageWriteParam)
            writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionType(compression);
    param.setTopDown(true);
    writer.write(null, new IIOImage(src, null, null), param);
    writer.dispose();
    ios.flush();
    ios.close();

    BufferedImage dst = ImageIO.read(fout);

    verify(dst);
}
 
Example 10
Source File: BitDepth.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private File testWriteRGB(String format, int type) throws IOException {

        BufferedImage bi = new BufferedImage(width, height, type);
        Graphics2D g = bi.createGraphics();

        Color white = new Color(255, 255, 255);
        Color red = new Color(255, 0, 0);
        Color green = new Color(0, 255, 0);
        Color blue = new Color(0, 0, 255);

        g.setColor(white);
        g.fillRect(0, 0, width, height);
        g.setColor(red);
        g.fillRect(10, 10, 20, 20);
        g.setColor(green);
        g.fillRect(30, 30, 20, 20);
        g.setColor(blue);
        g.fillRect(50, 50, 20, 20);

        ImageTypeSpecifier spec = new ImageTypeSpecifier(bi);
        Iterator<ImageWriter> writers = ImageIO.getImageWriters(spec, format);
        File file = new File("BitDepth_" + biTypeNames[type] + "." + format);
        if (!writers.hasNext()) {
            System.out.println("\tNo writers available for type " + biTypeNames[type]
                               + " BufferedImage!");
        } else {
            ImageWriter writer = writers.next();
            try (ImageOutputStream out = ImageIO.createImageOutputStream(file)) {
                writer.setOutput(out);
                writer.write(bi);
            } catch (Exception e) {
                System.out.println("\tCan't write a type " +  biTypeNames[type]
                           + " BufferedImage!");
                return null;
            }
        }

        return file;
    }
 
Example 11
Source File: EncodeSubImageTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private void write(File f, boolean subsample) throws IOException {
    ImageOutputStream ios = ImageIO.createImageOutputStream(f);

    writer.setOutput(ios);
    ImageWriteParam p = writer.getDefaultWriteParam();
    if (subsample) {
        p.setSourceSubsampling(subSampleX, subSampleY, 0, 0);
    }
    writer.write(null, new IIOImage(img, null, null), p);
    ios.close();
    writer.reset();
}
 
Example 12
Source File: BaseImageIoTest.java    From java-image-processing-survival-guide with Apache License 2.0 5 votes vote down vote up
@Override
public void writeBufferedImage(BufferedImage bufferedImage, float quality, int dpi, String formatName, File targetFile) throws Exception {

    System.out.println("Saving " + targetFile.getPath());

    if (formatName.equalsIgnoreCase("jpg") || formatName.equalsIgnoreCase("jpeg")) {
        JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix(formatName).next();
        ImageWriteParam writeParam = imageWriter.getDefaultWriteParam();
        ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
        IIOMetadata metadata = imageWriter.getDefaultImageMetadata(typeSpecifier, writeParam);

        if (formatName.equalsIgnoreCase("jpg") || formatName.equalsIgnoreCase("jpeg")) {
            Element tree = (Element) metadata.getAsTree("javax_imageio_jpeg_image_1.0");
            Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
            jfif.setAttribute("Xdensity", Integer.toString(dpi));
            jfif.setAttribute("Ydensity", Integer.toString(dpi));
            jfif.setAttribute("resUnits", "1");
            metadata.setFromTree("javax_imageio_jpeg_image_1.0", tree);
        }

        if (quality >= 0 && quality <= 1f) {
            JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
            jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
            jpegParams.setCompressionQuality(quality);
        }

        FileOutputStream os = new FileOutputStream(targetFile);
        final ImageOutputStream stream = ImageIO.createImageOutputStream(os);

        try {
            imageWriter.setOutput(stream);
            imageWriter.write(metadata, new IIOImage(bufferedImage, null, metadata), writeParam);
        } finally {
            stream.close();
        }
    } else {
        writeBufferedImage(bufferedImage, formatName, targetFile);
    }
}
 
Example 13
Source File: ImageIOHelper.java    From JewelCrawler with GNU General Public License v3.0 5 votes vote down vote up
public static File createImage(File imageFile, String imageFormat) {
	File tempFile = null;
	try {
		Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
		ImageReader reader = readers.next();

		ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
		reader.setInput(iis);
		// Read the stream metadata
		IIOMetadata streamMetadata = reader.getStreamMetadata();

		// Set up the writeParam
		TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
		tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

		// Get tif writer and set output to file
		Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("tiff");
		ImageWriter writer = writers.next();

		BufferedImage bi = reader.read(0);
		IIOImage image = new IIOImage(bi, null, reader.getImageMetadata(0));
		tempFile = tempImageFile(imageFile);
		ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile);
		writer.setOutput(ios);
		writer.write(streamMetadata, image, tiffWriteParam);
		ios.close();

		writer.dispose();
		reader.dispose();
	} catch (Exception exc) {
		exc.printStackTrace();
	}
	return tempFile;
}
 
Example 14
Source File: TopDownTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static void writeWithCompression(BufferedImage src,
                                         String compression) throws IOException
{
    System.out.println("Compression: " + compression);
    ImageWriter writer = ImageIO.getImageWritersByFormatName("BMP").next();
    if (writer == null) {
        throw new RuntimeException("Test failed: no bmp writer available");
    }
    File fout = File.createTempFile(compression + "_", ".bmp",
                                    new File("."));

    ImageOutputStream ios = ImageIO.createImageOutputStream(fout);
    writer.setOutput(ios);

    BMPImageWriteParam param = (BMPImageWriteParam)
            writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionType(compression);
    param.setTopDown(true);
    writer.write(null, new IIOImage(src, null, null), param);
    writer.dispose();
    ios.flush();
    ios.close();

    BufferedImage dst = ImageIO.read(fout);

    verify(dst);
}
 
Example 15
Source File: RGBAnimationTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public void doTest() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    writer.reset();
    ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
    writer.setOutput(ios);

    ImageWriteParam wparam = prepareWriteParam();

    IIOMetadata streamMetadata = prepareStreamMetadata(wparam);

    writer.prepareWriteSequence(streamMetadata);

    for (int i = 0; i < frames.length; i++) {
        BufferedImage src = frames[i].getImage();
        IIOMetadata imageMetadata = prepareImageMetadata(i, src, wparam);
        IIOImage img = new IIOImage(src,  null, imageMetadata);

        writer.writeToSequence(img, wparam);
    }
    writer.endWriteSequence();
    ios.flush();
    ios.close();

    if (doSave) {
        File f = File.createTempFile("wr_test_", "." + format, new File("."));
        System.out.println("Save to file: " + f.getCanonicalPath());
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(baos.toByteArray());
        fos.flush();
        fos.close();
    }
    // read result
    reader.reset();
    ByteArrayInputStream bais =
            new ByteArrayInputStream(baos.toByteArray());
    reader.setInput(ImageIO.createImageInputStream(bais));

    int minIndex = reader.getMinIndex();
    int numImages = reader.getNumImages(true);

    for (int i = 0; i < numImages; i++) {
        BufferedImage dst = reader.read(i + minIndex);
        frames[i].checkResult(dst);
    }
}
 
Example 16
Source File: WriteAfterAbort.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
private void test(final ImageWriter writer) throws IOException {
    // Image initialization
    final BufferedImage imageWrite = new BufferedImage(WIDTH, HEIGHT,
                                                       TYPE_BYTE_BINARY);
    final Graphics2D g = imageWrite.createGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, WIDTH, HEIGHT);
    g.dispose();

    // File initialization
    final File file = File.createTempFile("temp", ".img");
    file.deleteOnExit();
    final FileOutputStream fos = new SkipWriteOnAbortOutputStream(file);
    final ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
    writer.setOutput(ios);
    writer.addIIOWriteProgressListener(this);

    // This write will be aborted, and file will not be touched
    writer.write(imageWrite);
    if (!isStartedCalled) {
        throw new RuntimeException("Started should be called");
    }
    if (!isProgressCalled) {
        throw new RuntimeException("Progress should be called");
    }
    if (!isAbortCalled) {
        throw new RuntimeException("Abort should be called");
    }
    if (isCompleteCalled) {
        throw new RuntimeException("Complete should not be called");
    }
    // Flush aborted data
    ios.flush();

    // This write should be completed successfully and the file should
    // contain correct image data.
    abortFlag = false;
    isAbortCalled = false;
    isCompleteCalled = false;
    isProgressCalled = false;
    isStartedCalled = false;
    writer.write(imageWrite);

    if (!isStartedCalled) {
        throw new RuntimeException("Started should be called");
    }
    if (!isProgressCalled) {
        throw new RuntimeException("Progress should be called");
    }
    if (isAbortCalled) {
        throw new RuntimeException("Abort should not be called");
    }
    if (!isCompleteCalled) {
        throw new RuntimeException("Complete should be called");
    }
    writer.dispose();
    ios.close();

    // Validates content of the file.
    final BufferedImage imageRead = ImageIO.read(file);
    for (int x = 0; x < WIDTH; ++x) {
        for (int y = 0; y < HEIGHT; ++y) {
            if (imageRead.getRGB(x, y) != imageWrite.getRGB(x, y)) {
                throw new RuntimeException("Test failed.");
            }
        }
    }
}
 
Example 17
Source File: BMPSubsamplingTest.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public BMPSubsamplingTest() throws IOException {
    ImageWriter writer =
        ImageIO.getImageWritersByFormatName(format).next();

    ImageWriteParam wparam = writer.getDefaultWriteParam();
    wparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    String[] types = wparam.getCompressionTypes();
    for (int t = 0; t < img_types.length; t++) {
        int img_type = img_types[t];
        System.out.println("Test for " + getImageTypeName(img_type));
        BufferedImage image = getTestImage(img_type);

        ImageTypeSpecifier specifier = new ImageTypeSpecifier(image);

        if (!writer.getOriginatingProvider().canEncodeImage(specifier)) {
            System.out.println("Writer does not support encoding this buffered image type.");
            continue;
        }

        for(int i=0; i<types.length; i++) {
            if ("BI_JPEG".equals(types[i])) {
                // exclude BI_JPEG from automatic test
                // due to color diffusion effect on the borders.
                continue;
            }

            if (canEncodeImage(types[i], specifier, img_type)) {
                System.out.println("compression type: " + types[i] +
                    " Supported for " + getImageTypeName(img_type));
            } else {
                System.out.println("compression type: " + types[i] +
                    " NOT Supported for " + getImageTypeName(img_type));
                continue;
            }
            ImageWriteParam imageWriteParam = getImageWriteParam(writer, types[i]);

            imageWriteParam.setSourceSubsampling(srcXSubsampling,
                                                 srcYSubsampling,
                                                 0, 0);
            File outputFile = new File("subsampling_test_" +
                getImageTypeName(img_type) + "__" +
                types[i] + ".bmp");
            ImageOutputStream ios =
                ImageIO.createImageOutputStream(outputFile);
            writer.setOutput(ios);

            IIOImage iioImg = new IIOImage(image, null, null);

            writer.write(null, iioImg, imageWriteParam);

            ios.flush();
            ios.close();

            BufferedImage outputImage = ImageIO.read(outputFile);
            checkTestImage(outputImage);
        }
    }
}
 
Example 18
Source File: PNGWriter.java    From FastAsyncWorldedit with GNU General Public License v3.0 4 votes vote down vote up
public PNGWriter(OutputStream out) throws IOException {
    this.out = ImageIO.createImageOutputStream(out);
}
 
Example 19
Source File: BMPSubsamplingTest.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public BMPSubsamplingTest() throws IOException {
    ImageWriter writer =
        ImageIO.getImageWritersByFormatName(format).next();

    ImageWriteParam wparam = writer.getDefaultWriteParam();
    wparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    String[] types = wparam.getCompressionTypes();
    for (int t = 0; t < img_types.length; t++) {
        int img_type = img_types[t];
        System.out.println("Test for " + getImageTypeName(img_type));
        BufferedImage image = getTestImage(img_type);

        ImageTypeSpecifier specifier = new ImageTypeSpecifier(image);

        if (!writer.getOriginatingProvider().canEncodeImage(specifier)) {
            System.out.println("Writer does not support encoding this buffered image type.");
            continue;
        }

        for(int i=0; i<types.length; i++) {
            if ("BI_JPEG".equals(types[i])) {
                // exclude BI_JPEG from automatic test
                // due to color diffusion effect on the borders.
                continue;
            }

            if (canEncodeImage(types[i], specifier, img_type)) {
                System.out.println("compression type: " + types[i] +
                    " Supported for " + getImageTypeName(img_type));
            } else {
                System.out.println("compression type: " + types[i] +
                    " NOT Supported for " + getImageTypeName(img_type));
                continue;
            }
            ImageWriteParam imageWriteParam = getImageWriteParam(writer, types[i]);

            imageWriteParam.setSourceSubsampling(srcXSubsampling,
                                                 srcYSubsampling,
                                                 0, 0);
            File outputFile = new File("subsampling_test_" +
                getImageTypeName(img_type) + "__" +
                types[i] + ".bmp");
            ImageOutputStream ios =
                ImageIO.createImageOutputStream(outputFile);
            writer.setOutput(ios);

            IIOImage iioImg = new IIOImage(image, null, null);

            writer.write(null, iioImg, imageWriteParam);

            ios.flush();
            ios.close();

            BufferedImage outputImage = ImageIO.read(outputFile);
            checkTestImage(outputImage);
        }
    }
}
 
Example 20
Source File: CoverArtController.java    From airsonic-advanced with GNU General Public License v3.0 4 votes vote down vote up
private Path getCachedImage(CoverArtRequest request, int size) throws IOException {
        String hash = DigestUtils.md5Hex(request.getKey());
        String encoding = request.getCoverArt() != null ? "jpeg" : "png";
        Path cachedImage = getImageCacheDirectory(size).resolve(hash + "." + encoding);

        // Synchronize to avoid concurrent writing to the same file.
        synchronized (hash.intern()) {

            // Is cache missing or obsolete?
            if (!Files.exists(cachedImage) || request.lastModified().isAfter(FileUtil.lastModified(cachedImage))) {
//                LOG.info("Cache MISS - " + request + " (" + size + ")");
                ImageWriter writer = null;

                try (OutputStream os = Files.newOutputStream(cachedImage);
                        BufferedOutputStream bos = new BufferedOutputStream(os);
                        ImageOutputStream out = ImageIO.createImageOutputStream(bos)) {
                    semaphore.acquire();
                    BufferedImage image = request.createImage(size);
                    if (image == null) {
                        throw new Exception("Unable to decode image.");
                    }
                    writer = ImageIO.getImageWritersByFormatName(encoding).next();

                    float quality = (float) (settingsService.getCoverArtQuality() / 100.0);
                    ImageWriteParam params = writer.getDefaultWriteParam();
                    params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                    params.setCompressionQuality(quality); // default is 0.75

                    writer.setOutput(out);
                    writer.write(null, new IIOImage(image, null, null), params);

                } catch (Throwable x) {
                    // Delete corrupt (probably empty) thumbnail cache.
                    LOG.warn("Failed to create thumbnail for {}", request, x);
                    FileUtil.delete(cachedImage);
                    throw new IOException("Failed to create thumbnail for " + request + ". " + x.getMessage());
                } finally {
                    if (writer != null) {
                        writer.dispose();
                        writer = null;
                    }
                    semaphore.release();
                }
            } else {
//                LOG.info("Cache HIT - " + request + " (" + size + ")");
            }
            return cachedImage;
        }
    }