javax.imageio.stream.ImageOutputStream Java Examples

The following examples show how to use javax.imageio.stream.ImageOutputStream. 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: ShortHistogramTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
protected File writeImageWithHist(BufferedImage bi) throws IOException {
    File f = File.createTempFile("hist_", ".png", new File("."));

    ImageWriter writer = ImageIO.getImageWritersByFormatName("PNG").next();

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

    ImageWriteParam param = writer.getDefaultWriteParam();
    ImageTypeSpecifier type = new ImageTypeSpecifier(bi);

    IIOMetadata imgMetadata = writer.getDefaultImageMetadata(type, param);

    /* add hIST node to image metadata */
    imgMetadata = upgradeMetadata(imgMetadata, bi);

    IIOImage iio_img = new IIOImage(bi,
                                    null, // no thumbnails
                                    imgMetadata);

    writer.write(iio_img);
    ios.flush();
    ios.close();
    return f;
}
 
Example #2
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 #3
Source File: OutputImageTests.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    final Context ictx = (Context)ctx;
    final ImageWriter writer = ictx.writer;
    final BufferedImage image = ictx.image;
    do {
        try {
            ImageOutputStream ios = ictx.createImageOutputStream();
            writer.setOutput(ios);
            writer.write(image);
            writer.reset();
            ios.close();
            ictx.closeOriginalStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } while (--numReps >= 0);
}
 
Example #4
Source File: PNGImageWriterSpi.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public PNGImageWriterSpi() {
      super(vendorName,
            version,
            names,
            suffixes,
            MIMETypes,
            writerClassName,
            new Class[] { ImageOutputStream.class },
            readerSpiNames,
            false,
            null, null,
            null, null,
            true,
            PNGMetadata.nativeMetadataFormatName,
            "com.sun.imageio.plugins.png.PNGMetadataFormat",
            null, null
            );
}
 
Example #5
Source File: ImageIOGreyScale.java    From multimedia-indexing with Apache License 2.0 6 votes vote down vote up
/**
 * Writes an image using an arbitrary <code>ImageWriter</code> that supports the given format to a
 * <code>File</code>. If there is already a <code>File</code> present, its contents are discarded.
 * 
 * @param im
 *            a <code>RenderedImage</code> to be written.
 * @param formatName
 *            a <code>String</code> containg the informal name of the format.
 * @param output
 *            a <code>File</code> to be written to.
 * 
 * @return <code>false</code> if no appropriate writer is found.
 * 
 * @exception IllegalArgumentException
 *                if any parameter is <code>null</code>.
 * @exception IOException
 *                if an error occurs during writing.
 */
public static boolean write(RenderedImage im, String formatName, File output) throws IOException {
	if (output == null) {
		throw new IllegalArgumentException("output == null!");
	}
	ImageOutputStream stream = null;
	try {
		output.delete();
		stream = createImageOutputStream(output);
	} catch (IOException e) {
		throw new IIOException("Can't create output stream!", e);
	}

	boolean val;
	try {
		val = write(im, formatName, stream);
	} finally {
		stream.close();
	}
	return val;
}
 
Example #6
Source File: JFIFMarkerSegment.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Writes out a new JFXX extension segment, without saving it.
 */
private void writeJFXXSegment(int index,
                              BufferedImage thumbnail,
                              ImageOutputStream ios,
                              JPEGImageWriter writer) throws IOException {
    JFIFExtensionMarkerSegment jfxx = null;
    try {
         jfxx = new JFIFExtensionMarkerSegment(thumbnail);
    } catch (IllegalThumbException e) {
        writer.warningOccurred
            (JPEGImageWriter.WARNING_ILLEGAL_THUMBNAIL);
        return;
    }
    writer.thumbnailStarted(index);
    jfxx.write(ios, writer);
    writer.thumbnailComplete();
}
 
Example #7
Source File: GIFImageWriterSpi.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public GIFImageWriterSpi() {
    super(vendorName,
          version,
          names,
          suffixes,
          MIMETypes,
          writerClassName,
          new Class[] { ImageOutputStream.class },
          readerSpiNames,
          true,
          GIFWritableStreamMetadata.NATIVE_FORMAT_NAME,
          "com.sun.imageio.plugins.gif.GIFStreamMetadataFormat",
          null, null,
          true,
          GIFWritableImageMetadata.NATIVE_FORMAT_NAME,
          "com.sun.imageio.plugins.gif.GIFImageMetadataFormat",
          null, null
          );
}
 
Example #8
Source File: BMPImageWriterSpi.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
public BMPImageWriterSpi() {
    super("Oracle Corporation",
          "1.0",
          formatNames,
          entensions,
          mimeType,
          "com.sun.imageio.plugins.bmp.BMPImageWriter",
          new Class<?>[] { ImageOutputStream.class },
          readerSpiNames,
          false,
          null, null, null, null,
          true,
          BMPMetadata.nativeMetadataFormatName,
          "com.sun.imageio.plugins.bmp.BMPMetadataFormat",
          null, null);
}
 
Example #9
Source File: SunJPEGEncoderAdapter.java    From ECG-Viewer with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Encodes an image in JPEG format and writes it to an output stream.
 *
 * @param bufferedImage  the image to be encoded (<code>null</code> not
 *     permitted).
 * @param outputStream  the OutputStream to write the encoded image to
 *     (<code>null</code> not permitted).
 *
 * @throws IOException if there is an I/O problem.
 * @throws NullPointerException if <code>bufferedImage</code> is
 *     <code>null</code>.
 */
@Override
public void encode(BufferedImage bufferedImage, OutputStream outputStream)
        throws IOException {
    ParamChecks.nullNotPermitted(bufferedImage, "bufferedImage");
    ParamChecks.nullNotPermitted(outputStream, "outputStream");
    Iterator iterator = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter writer = (ImageWriter) iterator.next();
    ImageWriteParam p = writer.getDefaultWriteParam();
    p.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    p.setCompressionQuality(this.quality);
    ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
    writer.setOutput(ios);
    writer.write(null, new IIOImage(bufferedImage, null, null), p);
    ios.flush();
    writer.dispose();
    ios.close();
}
 
Example #10
Source File: LZWCompressor.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param out destination for compressed data
 * @param codeSize the initial code size for the LZW compressor
 * @param TIFF flag indicating that TIFF lzw fudge needs to be applied
 * @exception IOException if underlying output stream error
 **/
public LZWCompressor(ImageOutputStream out, int codeSize, boolean TIFF)
    throws IOException
{
    bf = new BitFile(out, !TIFF); // set flag for GIF as NOT tiff
    this.codeSize = codeSize;
    tiffFudge = TIFF;
    clearCode = 1 << codeSize;
    endOfInfo = clearCode + 1;
    numBits = codeSize + 1;

    limit = (1 << numBits) - 1;
    if (tiffFudge) {
        --limit;
    }

    prefix = (short)0xFFFF;
    lzss = new LZWStringTable();
    lzss.clearTable(codeSize);
    bf.writeBits(clearCode, numBits);
}
 
Example #11
Source File: JFIFMarkerSegment.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
void write(ImageOutputStream ios,
           JPEGImageWriter writer) throws IOException {
    super.write(ios, writer); // width and height
    // Write the palette (must be 768 bytes)
    byte [] palette = new byte[768];
    IndexColorModel icm = (IndexColorModel) thumbnail.getColorModel();
    byte [] reds = new byte [256];
    byte [] greens = new byte [256];
    byte [] blues = new byte [256];
    icm.getReds(reds);
    icm.getGreens(greens);
    icm.getBlues(blues);
    for (int i = 0; i < 256; i++) {
        palette[i*3] = reds[i];
        palette[i*3+1] = greens[i];
        palette[i*3+2] = blues[i];
    }
    ios.write(palette);
    writePixels(ios, writer);
}
 
Example #12
Source File: OutputImageTests.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    final Context ictx = (Context)ctx;
    final ImageWriter writer = ictx.writer;
    final BufferedImage image = ictx.image;
    do {
        try {
            ImageOutputStream ios = ictx.createImageOutputStream();
            writer.setOutput(ios);
            writer.write(image);
            writer.reset();
            ios.close();
            ictx.closeOriginalStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } while (--numReps >= 0);
}
 
Example #13
Source File: OutputImageTests.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    final Context ictx = (Context)ctx;
    final ImageWriter writer = ictx.writer;
    final BufferedImage image = ictx.image;
    do {
        try {
            ImageOutputStream ios = ictx.createImageOutputStream();
            writer.setOutput(ios);
            writer.write(image);
            writer.reset();
            ios.close();
            ictx.closeOriginalStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } while (--numReps >= 0);
}
 
Example #14
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 #15
Source File: JFIFMarkerSegment.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
void write(ImageOutputStream ios,
           JPEGImageWriter writer) throws IOException {
    super.write(ios, writer); // width and height
    // Write the palette (must be 768 bytes)
    byte [] palette = new byte[768];
    IndexColorModel icm = (IndexColorModel) thumbnail.getColorModel();
    byte [] reds = new byte [256];
    byte [] greens = new byte [256];
    byte [] blues = new byte [256];
    icm.getReds(reds);
    icm.getGreens(greens);
    icm.getBlues(blues);
    for (int i = 0; i < 256; i++) {
        palette[i*3] = reds[i];
        palette[i*3+1] = greens[i];
        palette[i*3+2] = blues[i];
    }
    ios.write(palette);
    writePixels(ios, writer);
}
 
Example #16
Source File: OutputImageTests.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    final Context ictx = (Context)ctx;
    final ImageWriter writer = ictx.writer;
    final BufferedImage image = ictx.image;
    do {
        try {
            ImageOutputStream ios = ictx.createImageOutputStream();
            writer.setOutput(ios);
            writer.write(image);
            writer.reset();
            ios.close();
            ictx.closeOriginalStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } while (--numReps >= 0);
}
 
Example #17
Source File: ImageHelper.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Can change this to choose a better compression level as the default
 * 
 * @param image
 * @param scaledImage
 * @return
 */
private static boolean writeTo(BufferedImage image, File scaledImage, Size scaledSize, String outputFormat) {
    try {
        if (!StringHelper.containsNonWhitespace(outputFormat)) {
            outputFormat = OUTPUT_FORMAT;
        }

        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(outputFormat);
        if (writers.hasNext()) {
            ImageWriter writer = writers.next();
            ImageWriteParam iwp = getOptimizedImageWriteParam(writer, scaledSize);
            IIOImage iiOImage = new IIOImage(image, null, null);
            ImageOutputStream iOut = new FileImageOutputStream(scaledImage);
            writer.setOutput(iOut);
            writer.write(null, iiOImage, iwp);
            writer.dispose();
            iOut.flush();
            iOut.close();
            return true;
        } else {
            return ImageIO.write(image, outputFormat, scaledImage);
        }
    } catch (IOException e) {
        return false;
    }
}
 
Example #18
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 #19
Source File: SunJPEGEncoderAdapter.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Encodes an image in JPEG format and writes it to an output stream.
 *
 * @param bufferedImage  the image to be encoded (<code>null</code> not
 *     permitted).
 * @param outputStream  the OutputStream to write the encoded image to
 *     (<code>null</code> not permitted).
 *
 * @throws IOException if there is an I/O problem.
 * @throws NullPointerException if <code>bufferedImage</code> is
 *     <code>null</code>.
 */
@Override
public void encode(BufferedImage bufferedImage, OutputStream outputStream)
        throws IOException {
    ParamChecks.nullNotPermitted(bufferedImage, "bufferedImage");
    ParamChecks.nullNotPermitted(outputStream, "outputStream");
    Iterator iterator = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter writer = (ImageWriter) iterator.next();
    ImageWriteParam p = writer.getDefaultWriteParam();
    p.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    p.setCompressionQuality(this.quality);
    ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
    writer.setOutput(ios);
    writer.write(null, new IIOImage(bufferedImage, null, null), p);
    ios.flush();
    writer.dispose();
    ios.close();
}
 
Example #20
Source File: BMPImageWriterSpi.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public BMPImageWriterSpi() {
    super("Oracle Corporation",
          "1.0",
          formatNames,
          entensions,
          mimeType,
          "com.sun.imageio.plugins.bmp.BMPImageWriter",
          new Class[] { ImageOutputStream.class },
          readerSpiNames,
          false,
          null, null, null, null,
          true,
          BMPMetadata.nativeMetadataFormatName,
          "com.sun.imageio.plugins.bmp.BMPMetadataFormat",
          null, null);
}
 
Example #21
Source File: WebPWriterTest.java    From webp-imageio with Apache License 2.0 5 votes vote down vote up
/**
 * Test method tests {@link WebPWriter} with image resize options.
 *
 * @throws IOException
 *            the test fails.
 */
@Test(dataProvider = "createImagesWithScaleOptions", enabled = true)
public void testImageWriterScale(final RenderedImage image, final float xScale,
      final float yScale, final String outputName) throws IOException {
   final String extension = outputName.substring(outputName.lastIndexOf(".") + 1);

   // Scale the image.
   final RenderedOp scaledImage = ScaleDescriptor.create(image, xScale, yScale, 0f, 0f,
         Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2), null);

   // get writer
   final ImageWriter imgWriter = ImageIO.getImageWritersByFormatName(extension).next();
   final ImageWriteParam imgWriteParams = new WebPWriteParam(null);
   final String testName = "ScaleOptions";
   final File file = createOutputFile(testName, outputName);
   final ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(file);
   try {
      imgWriter.setOutput(imageOutputStream);
      imgWriter.write(null, new IIOImage(scaledImage, null, null), imgWriteParams);
      final int length = (int) imageOutputStream.length();
      assertTrue(length > 0);
   } finally {
      try {
         imageOutputStream.close();
      } catch (final IOException e) {
      }
   }
}
 
Example #22
Source File: FileImageOutputStreamSpi.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public ImageOutputStream createOutputStreamInstance(Object output,
                                                    boolean useCache,
                                                    File cacheDir) {
    if (output instanceof File) {
        try {
            return new FileImageOutputStream((File)output);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    } else {
        throw new IllegalArgumentException();
    }
}
 
Example #23
Source File: JFIFMarkerSegment.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
void writePixels(ImageOutputStream ios,
                 JPEGImageWriter writer) throws IOException {
    if ((thumbWidth > MAX_THUMB_WIDTH)
        || (thumbHeight > MAX_THUMB_HEIGHT)) {
        writer.warningOccurred(JPEGImageWriter.WARNING_THUMB_CLIPPED);
    }
    thumbWidth = Math.min(thumbWidth, MAX_THUMB_WIDTH);
    thumbHeight = Math.min(thumbHeight, MAX_THUMB_HEIGHT);
    int [] data = thumbnail.getRaster().getPixels(0, 0,
                                                  thumbWidth,
                                                  thumbHeight,
                                                  (int []) null);
    writeThumbnailData(ios, data, writer);
}
 
Example #24
Source File: OutputStreamTests.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    final Context octx = (Context)ctx;
    try {
        do {
            ImageOutputStream ios = octx.createImageOutputStream();
            ios.close();
            octx.closeOriginalStream();
        } while (--numReps >= 0);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #25
Source File: OutputStreamTests.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    final Context octx = (Context)ctx;
    try {
        do {
            ImageOutputStream ios = octx.createImageOutputStream();
            ios.close();
            octx.closeOriginalStream();
        } while (--numReps >= 0);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #26
Source File: EncodeSubImageTest.java    From jdk8u_jdk 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 #27
Source File: EncodeSubImageTest.java    From openjdk-jdk8u 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 #28
Source File: JFIFMarkerSegment.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes the data for this segment to the stream in
 * valid JPEG format.  The length written takes the thumbnail
 * width and height into account.  If necessary, the thumbnail
 * is clipped to 255 x 255 and a warning is sent to the writer
 * argument.  Progress updates are sent to the writer argument.
 */
void write(ImageOutputStream ios,
           BufferedImage thumb,
           JPEGImageWriter writer) throws IOException {
    int thumbWidth = 0;
    int thumbHeight = 0;
    int thumbLength = 0;
    int [] thumbData = null;
    if (thumb != null) {
        // Clip if necessary and get the data in thumbData
        thumbWidth = thumb.getWidth();
        thumbHeight = thumb.getHeight();
        if ((thumbWidth > MAX_THUMB_WIDTH)
            || (thumbHeight > MAX_THUMB_HEIGHT)) {
            writer.warningOccurred(JPEGImageWriter.WARNING_THUMB_CLIPPED);
        }
        thumbWidth = Math.min(thumbWidth, MAX_THUMB_WIDTH);
        thumbHeight = Math.min(thumbHeight, MAX_THUMB_HEIGHT);
        thumbData = thumb.getRaster().getPixels(0, 0,
                                                thumbWidth, thumbHeight,
                                                (int []) null);
        thumbLength = thumbData.length;
    }
    length = DATA_SIZE + LENGTH_SIZE + thumbLength;
    writeTag(ios);
    byte [] id = {0x4A, 0x46, 0x49, 0x46, 0x00};
    ios.write(id);
    ios.write(majorVersion);
    ios.write(minorVersion);
    ios.write(resUnits);
    write2bytes(ios, Xdensity);
    write2bytes(ios, Ydensity);
    ios.write(thumbWidth);
    ios.write(thumbHeight);
    if (thumbData != null) {
        writer.thumbnailStarted(0);
        writeThumbnailData(ios, thumbData, writer);
        writer.thumbnailComplete();
    }
}
 
Example #29
Source File: RuntimeBuiltinLeafInfoImpl.java    From openjdk-jdk9 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 #30
Source File: WBMPImageWriter.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void setOutput(Object output) {
    super.setOutput(output); // validates output
    if (output != null) {
        if (!(output instanceof ImageOutputStream))
            throw new IllegalArgumentException(I18N.getString("WBMPImageWriter"));
        this.stream = (ImageOutputStream)output;
    } else
        this.stream = null;
}