Java Code Examples for javax.imageio.ImageWriter#dispose()

The following examples show how to use javax.imageio.ImageWriter#dispose() . 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: Img.java    From java-tool with Apache License 2.0 6 votes vote down vote up
public void writeTo(OutputStream os, String mimeType) {
    ImageWriter writer = ImageIO.getImageWritersByMIMEType(mimeType(mimeType)).next();
    dropAlphaChannelIfJPEG(writer);
    ImageWriteParam params = writer.getDefaultWriteParam();

    if (!Float.isNaN(compressionQuality) && params.canWriteCompressed()) {
        params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        params.setCompressionType(params.getCompressionTypes()[0]);
        params.setCompressionQuality(compressionQuality);
    }

    ImageOutputStream ios = os(os);
    writer.setOutput(ios);
    IIOImage image = new IIOImage(get(), null, null);
    try {
        writer.write(null, image, params);
    } catch (IOException e) {
        throw ioException(e);
    }
    IO.flush(ios);
    writer.dispose();
}
 
Example 2
Source File: CanWriteSequence.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void test(final ImageWriter writer) throws Exception {
    final File file = File.createTempFile("temp", ".img");
    file.deleteOnExit();
    final FileOutputStream fos = new FileOutputStream(file);
    final ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
    writer.setOutput(ios);
    final IIOMetadata data = writer.getDefaultStreamMetadata(null);

    if (writer.canWriteSequence()) {
        writer.prepareWriteSequence(data);
    } else {
        try {
            writer.prepareWriteSequence(data);
            throw new RuntimeException(
                    "UnsupportedOperationException was not thrown");
        } catch (final UnsupportedOperationException ignored) {
            // expected
        }
    }
    writer.dispose();
    ios.close();
}
 
Example 3
Source File: ResizePictureUtil.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
    * Reads the original image, creates a resized copy of it and returns its input stream. largestDimension is the
    * largest dimension of the resized image, the other dimension is scaled accordingly.
    *
    * @param image
    *            original image
    * @param largestDimension
    *            the largest dimension of the resized image, the other dimension is scaled accordingly
    * @return
    * @throws IOException
    * @throws UploadImageGalleryFileException
    */
   private static InputStream resize(BufferedImage image, int largestDimension) throws IOException {

//resize to 150 pixels max
BufferedImage outImage = Scalr.resize(image, Method.QUALITY, largestDimension);

//set jpeg compression quality explicitly
ImageWriter imageWriter = ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam jpgWriteParam = imageWriter.getDefaultWriteParam();
jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpgWriteParam.setCompressionQuality(.95f);

// buffer all data in a circular buffer of infinite sizes
CircularByteBuffer outputBuffer = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
ImageOutputStream ios = ImageIO.createImageOutputStream(outputBuffer.getOutputStream());
imageWriter.setOutput(ios);
IIOImage outputImage = new IIOImage(outImage, null, null);
imageWriter.write(null, outputImage, jpgWriteParam);
imageWriter.dispose();
outputBuffer.getOutputStream().close();

return outputBuffer.getInputStream();

   }
 
Example 4
Source File: JmeDesktopSystem.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void writeImageFile(OutputStream outStream, String format, ByteBuffer imageData, int width, int height) throws IOException {
    BufferedImage awtImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
    Screenshots.convertScreenShot2(imageData.asIntBuffer(), awtImage);

    ImageWriter writer = ImageIO.getImageWritersByFormatName(format).next();
    ImageWriteParam writeParam = writer.getDefaultWriteParam();

    if (format.equals("jpg")) {
        JPEGImageWriteParam jpegParam = (JPEGImageWriteParam) writeParam;
        jpegParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jpegParam.setCompressionQuality(0.95f);
    }

    awtImage = verticalFlip(awtImage);
    
    ImageOutputStream imgOut = new MemoryCacheImageOutputStream(outStream);
    writer.setOutput(imgOut);
    IIOImage outputImage = new IIOImage(awtImage, null, null);
    try {
        writer.write(null, outputImage, writeParam);
    } finally {
        imgOut.close();
        writer.dispose();
    }
}
 
Example 5
Source File: JPEGFactory.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private static ImageWriter getJPEGImageWriter() throws IOException
{
    ImageWriter writer = null;
    Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("jpeg");
    while (writers.hasNext())
    {
        if (writer != null)
        {
            writer.dispose();
        }
        writer = writers.next();
        if (writer == null)
        {
            continue;
        }
        // PDFBOX-3566: avoid CLibJPEGImageWriter, which is not a JPEGImageWriteParam
        if (writer.getDefaultWriteParam() instanceof JPEGImageWriteParam)
        {
            return writer;
        }
    }
    throw new IOException("No ImageWriter found for JPEG format");
}
 
Example 6
Source File: CanWriteSequence.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void test(final ImageWriter writer) throws Exception {
    final File file = File.createTempFile("temp", ".img");
    file.deleteOnExit();
    final FileOutputStream fos = new FileOutputStream(file);
    final ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
    writer.setOutput(ios);
    final IIOMetadata data = writer.getDefaultStreamMetadata(null);

    if (writer.canWriteSequence()) {
        writer.prepareWriteSequence(data);
    } else {
        try {
            writer.prepareWriteSequence(data);
            throw new RuntimeException(
                    "UnsupportedOperationException was not thrown");
        } catch (final UnsupportedOperationException ignored) {
            // expected
        }
    }
    writer.dispose();
    ios.close();
}
 
Example 7
Source File: ImageIOHelper.java    From JewelCrawler with GNU General Public License v3.0 6 votes vote down vote up
public static File createImage(BufferedImage bi) {
	File tempFile = null;
	try {
		tempFile = File.createTempFile("tempImageFile", ".tif");
		tempFile.deleteOnExit();
		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();

		IIOImage image = new IIOImage(bi, null, null);
		tempFile = tempImageFile(tempFile);
		ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile);
		writer.setOutput(ios);
		writer.write(null, image, tiffWriteParam);
		ios.close();
		writer.dispose();
	} catch (Exception exc) {
		exc.printStackTrace();
	}
	return tempFile;
}
 
Example 8
Source File: LUTCompareTest.java    From jdk8u_jdk 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 9
Source File: CanWriteSequence.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private static void test(final ImageWriter writer) throws Exception {
    final File file = File.createTempFile("temp", ".img");
    file.deleteOnExit();
    final FileOutputStream fos = new FileOutputStream(file);
    final ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
    writer.setOutput(ios);
    final IIOMetadata data = writer.getDefaultStreamMetadata(null);

    if (writer.canWriteSequence()) {
        writer.prepareWriteSequence(data);
    } else {
        try {
            writer.prepareWriteSequence(data);
            throw new RuntimeException(
                    "UnsupportedOperationException was not thrown");
        } catch (final UnsupportedOperationException ignored) {
            // expected
        }
    }
    writer.dispose();
    ios.close();
}
 
Example 10
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 11
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 12
Source File: WriteAfterAbort.java    From jdk8u-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 13
Source File: Pencode.java    From warp10-platform with Apache License 2.0 4 votes vote down vote up
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
  Object top = stack.pop();

  if (!(top instanceof processing.core.PGraphics)) {
    throw new WarpScriptException(getName() + " operates on a PGraphics instance.");
  }

  processing.core.PGraphics pg = (processing.core.PGraphics) top;
  
  pg.endDraw();
  
  BufferedImage bimage = new BufferedImage(pg.pixelWidth, pg.pixelHeight, BufferedImage.TYPE_INT_ARGB);
  bimage.setRGB(0, 0, pg.pixelWidth, pg.pixelHeight, pg.pixels, 0, pg.pixelWidth);
  Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("png");
  ImageWriter writer = null;
  if (iter.hasNext()) {
    writer = iter.next();
  }
  ImageWriteParam param = writer.getDefaultWriteParam();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  BufferedOutputStream output = new BufferedOutputStream(baos);
  
  try {
    writer.setOutput(ImageIO.createImageOutputStream(output));
    writer.write(null, new IIOImage(bimage, null, null), param);
  } catch (IOException ioe) {
    throw new WarpScriptException(getName() + " error while encoding PGraphics.", ioe);
  }
  
  writer.dispose();

  StringBuilder sb = new StringBuilder("data:image/png;base64,");
  sb.append(Base64.encodeBase64String(baos.toByteArray()));
  
  stack.push(sb.toString());

  //
  // Re-issue a 'beginDraw' so we can continue using the PGraphics instance
  //
  
  pg.beginDraw();

  return stack;
}
 
Example 14
Source File: BooleanAttributes.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void test(String mimeType, boolean useStreamMeta,
                        String metaXml, String... boolXpaths)
    throws Exception
{
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType(mimeType).next();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageOutputStream ios = new MemoryCacheImageOutputStream(os);
    iw.setOutput(ios);
    ImageWriteParam param = null;
    IIOMetadata streamMeta = iw.getDefaultStreamMetadata(param);
    IIOMetadata imageMeta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), param);
    IIOMetadata meta = useStreamMeta ? streamMeta : imageMeta;
    Source src = new StreamSource(new StringReader(metaXml));
    DOMResult dst = new DOMResult();
    transform(src, dst);
    Document doc = (Document)dst.getNode();
    Element node = doc.getDocumentElement();
    String metaFormat = node.getNodeName();

    // Verify that the default metadata gets formatted correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, false);

    meta.mergeTree(metaFormat, node);

    // Verify that the merged metadata gets formatte correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, true);

    iw.write(streamMeta, new IIOImage(img, null, imageMeta), param);
    iw.dispose();
    ios.close();
    ImageReader ir = ImageIO.getImageReader(iw);
    byte[] bytes = os.toByteArray();
    if (bytes.length == 0)
        throw new AssertionError("Zero length image file");
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    ImageInputStream iis = new MemoryCacheImageInputStream(is);
    ir.setInput(iis);
    if (useStreamMeta) meta = ir.getStreamMetadata();
    else meta = ir.getImageMetadata(0);

    // Verify again after writing and re-reading the image
    verify(meta.getAsTree(metaFormat), boolXpaths, true);
}
 
Example 15
Source File: PNGCodec.java    From jpexs-decompiler with GNU General Public License v3.0 4 votes vote down vote up
@Override
public int process(Buffer in, Buffer out) {
    out.setMetaTo(in);
    out.format = outputFormat;
    if (in.isFlag(DISCARD)) {
        return CODEC_OK;
    }

    BufferedImage image = getBufferedImage(in);
    if (image == null) {
        out.setFlag(DISCARD);
        return CODEC_FAILED;
    }

    ByteArrayImageOutputStream tmp;
    if (out.data instanceof byte[]) {
        tmp = new ByteArrayImageOutputStream((byte[]) out.data);
    } else {
        tmp = new ByteArrayImageOutputStream();
    }

    try {
        ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
        ImageWriteParam iwParam = iw.getDefaultWriteParam();
        iw.setOutput(tmp);
        IIOImage img = new IIOImage(image, null, null);
        iw.write(null, img, iwParam);
        iw.dispose();

        out.setFlag(KEYFRAME);
        out.header = null;
        out.data = tmp.getBuffer();
        out.offset = 0;
        out.length = (int) tmp.getStreamPosition();
        return CODEC_OK;
    } catch (IOException ex) {
        ex.printStackTrace();
        out.setFlag(DISCARD);
        return CODEC_FAILED;
    }
}
 
Example 16
Source File: WriteAfterAbort.java    From hottub 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: BooleanAttributes.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public static void test(String mimeType, boolean useStreamMeta,
                        String metaXml, String... boolXpaths)
    throws Exception
{
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType(mimeType).next();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageOutputStream ios = new MemoryCacheImageOutputStream(os);
    iw.setOutput(ios);
    ImageWriteParam param = null;
    IIOMetadata streamMeta = iw.getDefaultStreamMetadata(param);
    IIOMetadata imageMeta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), param);
    IIOMetadata meta = useStreamMeta ? streamMeta : imageMeta;
    Source src = new StreamSource(new StringReader(metaXml));
    DOMResult dst = new DOMResult();
    transform(src, dst);
    Document doc = (Document)dst.getNode();
    Element node = doc.getDocumentElement();
    String metaFormat = node.getNodeName();

    // Verify that the default metadata gets formatted correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, false);

    meta.mergeTree(metaFormat, node);

    // Verify that the merged metadata gets formatte correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, true);

    iw.write(streamMeta, new IIOImage(img, null, imageMeta), param);
    iw.dispose();
    ios.close();
    ImageReader ir = ImageIO.getImageReader(iw);
    byte[] bytes = os.toByteArray();
    if (bytes.length == 0)
        throw new AssertionError("Zero length image file");
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    ImageInputStream iis = new MemoryCacheImageInputStream(is);
    ir.setInput(iis);
    if (useStreamMeta) meta = ir.getStreamMetadata();
    else meta = ir.getImageMetadata(0);

    // Verify again after writing and re-reading the image
    verify(meta.getAsTree(metaFormat), boolXpaths, true);
}
 
Example 18
Source File: BooleanAttributes.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void test(String mimeType, boolean useStreamMeta,
                        String metaXml, String... boolXpaths)
    throws Exception
{
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType(mimeType).next();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageOutputStream ios = new MemoryCacheImageOutputStream(os);
    iw.setOutput(ios);
    ImageWriteParam param = null;
    IIOMetadata streamMeta = iw.getDefaultStreamMetadata(param);
    IIOMetadata imageMeta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), param);
    IIOMetadata meta = useStreamMeta ? streamMeta : imageMeta;
    Source src = new StreamSource(new StringReader(metaXml));
    DOMResult dst = new DOMResult();
    transform(src, dst);
    Document doc = (Document)dst.getNode();
    Element node = doc.getDocumentElement();
    String metaFormat = node.getNodeName();

    // Verify that the default metadata gets formatted correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, false);

    meta.mergeTree(metaFormat, node);

    // Verify that the merged metadata gets formatte correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, true);

    iw.write(streamMeta, new IIOImage(img, null, imageMeta), param);
    iw.dispose();
    ios.close();
    ImageReader ir = ImageIO.getImageReader(iw);
    byte[] bytes = os.toByteArray();
    if (bytes.length == 0)
        throw new AssertionError("Zero length image file");
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    ImageInputStream iis = new MemoryCacheImageInputStream(is);
    ir.setInput(iis);
    if (useStreamMeta) meta = ir.getStreamMetadata();
    else meta = ir.getImageMetadata(0);

    // Verify again after writing and re-reading the image
    verify(meta.getAsTree(metaFormat), boolXpaths, true);
}
 
Example 19
Source File: WriteAfterAbort.java    From openjdk-jdk9 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 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;
        }
    }