Java Code Examples for javax.imageio.stream.ImageOutputStream

The following are top voted examples for showing how to use javax.imageio.stream.ImageOutputStream. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: shareMySheet   File: ImageTransformation.java   Source Code and License 10 votes vote down vote up
public static byte[] compress(BufferedImage image, float scale) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
    ImageWriter writer = writers.next();
    ImageWriteParam param = writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionQuality(scale);
    ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
    writer.setOutput(ios);
    writer.write(null, new IIOImage(image, null, null), param);
    byte[] data = baos.toByteArray();
    writer.dispose();
    return data;
}
 
Example 2
Project: jdk8u-jdk   File: JFIFMarkerSegment.java   Source Code and License 7 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 3
Project: incubator-netbeans   File: ScreenshotComponent.java   Source Code and License 6 votes vote down vote up
void save(File file) throws IOException {
    ImageWriter iw = null;
    String name = file.getName();
    int i = name.lastIndexOf('.');
    if (i >= 0) {
        String extension = name.substring(i + 1);
        Iterator<ImageWriter> imageWritersBySuffix = ImageIO.getImageWritersBySuffix(extension);
        if (imageWritersBySuffix.hasNext()) {
            iw = imageWritersBySuffix.next();
        }
    }
    if (iw != null) {
        file.delete();
        ImageOutputStream ios = ImageIO.createImageOutputStream(file);
        iw.setOutput(ios);
        try {
            iw.write((BufferedImage) image);
        } finally {
            iw.dispose();
            ios.flush();
            ios.close();
        }
    } else {
        ImageIO.write((BufferedImage) image, "PNG", file);
    }
}
 
Example 4
Project: JavaPPTX   File: PPPicture.java   Source Code and License 6 votes vote down vote up
private static byte[] convertToPNG(Image image) {
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   int width = image.getWidth(null);
   int height = image.getHeight(null);
   BufferedImage bi = new BufferedImage(width, height,
                                        BufferedImage.TYPE_INT_ARGB);
   Graphics2D g = bi.createGraphics();
   g.setComposite(AlphaComposite.Src);
   g.drawImage(image, 0, 0, null);
   g.dispose();
   ImageOutputStream ios = new MemoryCacheImageOutputStream(out);
   try {
      if (!ImageIO.write(bi, "PNG", ios)) {
         throw new IOException("ImageIO.write failed");
      }
      ios.close();
   } catch (IOException ex) {
      throw new RuntimeException("saveImage: " + ex.getMessage());
   }
   return out.toByteArray();
}
 
Example 5
Project: imagetozxspec   File: GifConverter.java   Source Code and License 6 votes vote down vote up
/**
 * Create the gif and clear down afterwards.
 * 
 * @return the gif byte data
 * @throws IOException if the output fails
 */
public byte[] createGif() throws IOException {
	try {
		ImageOutputStream ios = ImageIO.createImageOutputStream(baos); // N.b. not try with closure because we need to close the stream before returning
		ImageWriter iw = ImageIO.getImageWritersByFormatName("gif").next();	
		iw.setOutput(ios);
		iw.prepareWriteSequence(null);
		int index = 0;
		ImageWriteParam iwp = iw.getDefaultWriteParam();
		String frameDelay = String.valueOf(OptionsObject.getInstance().getGifDisplayTimeMillis() / 10L);
		log.debug("Frames size: {}, Free memory {}", frames.size(), Runtime.getRuntime().freeMemory());
		for (BufferedImage frame : frames) {
			IIOMetadata metadata = iw.getDefaultImageMetadata(new ImageTypeSpecifier(frame), iwp);
			configureMetaData(metadata, frameDelay, index++);
			iw.writeToSequence(new IIOImage(frame, null, metadata), null);
		}
		iw.endWriteSequence();
		ios.close();
		return baos.toByteArray();
	} finally {
		baos = null;
		frames = null;
	}
}
 
Example 6
Project: OpenJSharp   File: OutputImageTests.java   Source Code and License 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 7
Project: openjdk-jdk10   File: OutputImageTests.java   Source Code and License 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 8
Project: openjdk-jdk10   File: WriteBitsTest.java   Source Code and License 6 votes vote down vote up
private static void verify(ImageOutputStream ios,
                           long expstreampos, int expbitoffset)
    throws IOException, RuntimeException
{
    long actstreampos = ios.getStreamPosition();
    int actbitoffset = ios.getBitOffset();

    if ((actstreampos != expstreampos) ||
        (actbitoffset != expbitoffset))
    {
        System.err.println("Expected stream position: " + expstreampos +
                           " Actual: " + actstreampos);
        System.err.println("Expected bit offset: " + expbitoffset +
                           " Actual: " + actbitoffset);
        throw new RuntimeException("Test failed.");
    }
}
 
Example 9
Project: OpenJSharp   File: JFIFMarkerSegment.java   Source Code and License 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 10
Project: openjdk-jdk10   File: TIFFImageWriterSpi.java   Source Code and License 6 votes vote down vote up
public TIFFImageWriterSpi() {
    super("Oracle Corporation",
          "1.0",
          new String[] {"tif", "TIF", "tiff", "TIFF"},
          new String[] {"tif", "tiff"},
          new String[] {"image/tiff"},
          "com.sun.imageio.plugins.tiff.TIFFImageWriter",
          new Class<?>[] {ImageOutputStream.class},
          new String[] {"com.sun.imageio.plugins.tiff.TIFFImageReaderSpi"},
          false,
          TIFFStreamMetadata.NATIVE_METADATA_FORMAT_NAME,
          "com.sun.imageio.plugins.tiff.TIFFStreamMetadataFormat",
          null, null,
          false,
          TIFFImageMetadata.NATIVE_METADATA_FORMAT_NAME,
          "com.sun.imageio.plugins.tiff.TIFFImageMetadataFormat",
          null, null
          );
}
 
Example 11
Project: openjdk-jdk10   File: CompressionModeTest.java   Source Code and License 6 votes vote down vote up
private static void doTest(int mode) {
    String fileFormat = "bmp";
    try {
        ImageWriter iw = (ImageWriter)ImageIO.getImageWritersBySuffix(fileFormat).next();
        if(iw == null) {
            throw new RuntimeException("No available image writer for "
                                       + fileFormat
                                       + " Test failed.");
        }

        File file = new File("image." + fileFormat);
        ImageOutputStream ios = ImageIO.createImageOutputStream(file);
        iw.setOutput(ios);

        BufferedImage bimg = new BufferedImage(100,
                                               100, BufferedImage.TYPE_INT_RGB);
        Graphics g = bimg.getGraphics();
        g.setColor(Color.green);
        g.fillRect(0,0,100,100);

        ImageWriteParam param = iw.getDefaultWriteParam();

        param.setCompressionMode(mode);

        IIOMetadata meta = iw.getDefaultImageMetadata(new ImageTypeSpecifier(bimg),
                                                      param);

        IIOImage iioImg = new IIOImage(bimg, null, meta);
        iw.write(null, iioImg, param);
    } catch(Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Test failed.");
    }
}
 
Example 12
Project: OpenJSharp   File: JFIFMarkerSegment.java   Source Code and License 6 votes vote down vote up
void write(ImageOutputStream ios,
           JPEGImageWriter writer) throws IOException {
    int progInterval = data.length / 20;  // approx. every 5%
    if (progInterval == 0) {
        progInterval = 1;
    }
    for (int offset = 0;
         offset < data.length;) {
        int len = Math.min(progInterval, data.length-offset);
        ios.write(data, offset, len);
        offset += progInterval;
        float percentDone = ((float) offset * 100) / data.length;
        if (percentDone > 100.0F) {
            percentDone = 100.0F;
        }
        writer.thumbnailProgress (percentDone);
    }
}
 
Example 13
Project: OpenJSharp   File: GIFImageWriterSpi.java   Source Code and License 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 14
Project: springboot-training   File: ImageUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 根据质量压缩图片,不改变图片的尺寸
 * 
 * @param imgContent
 *            图片内容
 * @param quality
 *            缩放比例
 * @param extName
 *            后缀名
 * @return
 */
public byte[] compress(byte[] imgContent, float quality, String extName) {
	if (quality > 1 || quality <= 0 || imgContent == null || WakaUtils.string.isEmpty(extName)) {
		throw new ZhhrUtilException("压缩文件失败!入参为空");
	}
	try (InputStream is = new ByteArrayInputStream(imgContent);
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			ImageOutputStream ios = ImageIO.createImageOutputStream(os);) {
		BufferedImage image = ImageIO.read(is);

		Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(extName);
		ImageWriter writer = writers.next();
		writer.setOutput(ios);

		ImageWriteParam param = writer.getDefaultWriteParam();
		param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
		param.setCompressionQuality(quality);

		writer.write(null, new IIOImage(image, null, null), param);
		writer.dispose();

		return os.toByteArray();
	} catch (IOException e) {
		throw new ZhhrUtilException(e.getMessage(), e);
	}
}
 
Example 15
Project: OpenJSharp   File: BMPImageWriterSpi.java   Source Code and License 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 16
Project: OpenJSharp   File: LZWCompressor.java   Source Code and License 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 17
Project: openjdk-jdk10   File: DestTypeTest.java   Source Code and License 6 votes vote down vote up
public byte[] writeTest(BufferedImage bi,
                        ImageWriteParam p,
                        IIOMetadata m) throws IOException {
    ByteArrayOutputStream baos =
        new ByteArrayOutputStream();

    // write test image as jpeg
    ImageOutputStream ios =
        ImageIO.createImageOutputStream(baos);
    w.setOutput(ios);
    w.write(null,
            new IIOImage(bi, null, m),
            p);
    ios.close();
    return baos.toByteArray();
}
 
Example 18
Project: imageio-jnr   File: TurboJpegImageWriterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCanReuseWriter() throws IOException {
  ImageWriter writer = Streams.stream(ImageIO.getImageWritersByFormatName("jpeg"))
      .filter(TurboJpegImageWriter.class::isInstance)
      .findFirst().get();

  BufferedImage in = ImageIO.read(ClassLoader.getSystemResource("rgb.jpg"));
  ByteArrayOutputStream rgb = new ByteArrayOutputStream();
  try (ImageOutputStream ios = ImageIO.createImageOutputStream(rgb)) {
    writer.setOutput(ios);
    writer.write(null, new IIOImage(in, null, null), null);
  }
  rgb.flush();

  in = ImageIO.read(ClassLoader.getSystemResource("crop_aligned.jpg"));
  ByteArrayOutputStream bw = new ByteArrayOutputStream();
  try (ImageOutputStream ios = ImageIO.createImageOutputStream(bw)) {
    writer.setOutput(ios);
    writer.write(null, new IIOImage(in, null, null), null);
  }
  bw.flush();

  assertThat(rgb.toByteArray()).isNotEqualTo(bw.toByteArray());
}
 
Example 19
Project: jdk8u-jdk   File: LUTCompareTest.java   Source Code and License 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 20
Project: jdk8u-jdk   File: JFIFMarkerSegment.java   Source Code and License 6 votes vote down vote up
void write(ImageOutputStream ios,
           JPEGImageWriter writer) throws IOException {
    int progInterval = data.length / 20;  // approx. every 5%
    if (progInterval == 0) {
        progInterval = 1;
    }
    for (int offset = 0;
         offset < data.length;) {
        int len = Math.min(progInterval, data.length-offset);
        ios.write(data, offset, len);
        offset += progInterval;
        float percentDone = ((float) offset * 100) / data.length;
        if (percentDone > 100.0F) {
            percentDone = 100.0F;
        }
        writer.thumbnailProgress (percentDone);
    }
}
 
Example 21
Project: openjdk-jdk10   File: WriteProgressive.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Iterator witer = ImageIO.getImageWritersByFormatName("png");
    ImageWriter w = (ImageWriter)witer.next();

    File f = File.createTempFile("WriteProgressive", ".png");
    ImageOutputStream ios = ImageIO.createImageOutputStream(f);
    w.setOutput(ios);

    BufferedImage bi = new BufferedImage(100, 100,
                                         BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g = bi.createGraphics();
    Random r = new Random(10);
    for (int i = 0; i < 10000; i++) {
        Color c =
            new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
        g.setColor(c);
        g.fillRect(r.nextInt(100), r.nextInt(100), 1, 1);
    }

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

    ImageWriteParam param = w.getDefaultWriteParam();
    param.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);

    try {
        w.write(null, iioimage, param);
    } catch (NullPointerException npe) {
        throw new RuntimeException("Got NPE during write!");
    }

    ios.close();

    BufferedImage bi2 = ImageIO.read(f);
    f.delete();

    ImageCompare.compare(bi, bi2);
}
 
Example 22
Project: imageio-jnr   File: TurboJpegImageWriter.java   Source Code and License 5 votes vote down vote up
@Override
public void setOutput(Object output) {
  super.setOutput(output);
  if (output != null) {
    if (!(output instanceof ImageOutputStream)) {
      throw new IllegalArgumentException("Output not an ImageOutputStream");
    }
    this.stream = (ImageOutputStream) output;
  } else {
    this.stream = null;
  }
}
 
Example 23
Project: openjdk-jdk10   File: JFIFMarkerSegment.java   Source Code and License 5 votes vote down vote up
/**
 * Writes out a default JFIF marker segment to the given
 * output stream.  If {@code thumbnails} is not {@code null},
 * writes out the set of thumbnail images as JFXX marker segments, or
 * incorporated into the JFIF segment if appropriate.
 * If {@code iccProfile} is not {@code null},
 * writes out the profile after the JFIF segment using as many APP2
 * marker segments as necessary.
 */
static void writeDefaultJFIF(ImageOutputStream ios,
                             List<? extends BufferedImage> thumbnails,
                             ICC_Profile iccProfile,
                             JPEGImageWriter writer)
    throws IOException {

    JFIFMarkerSegment jfif = new JFIFMarkerSegment();
    jfif.writeWithThumbs(ios, thumbnails, writer);
    if (iccProfile != null) {
        writeICC(iccProfile, ios);
    }
}
 
Example 24
Project: openjdk-jdk10   File: RAFImageOutputStreamSpi.java   Source Code and License 5 votes vote down vote up
public ImageOutputStream createOutputStreamInstance(Object output,
                                                    boolean useCache,
                                                    File cacheDir) {
    if (output instanceof RandomAccessFile) {
        try {
            return new FileImageOutputStream((RandomAccessFile)output);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    } else {
        throw new IllegalArgumentException
            ("input not a RandomAccessFile!");
    }
}
 
Example 25
Project: openjdk-jdk10   File: BitFile.java   Source Code and License 5 votes vote down vote up
public BitFile(ImageOutputStream output, boolean blocks) {
    this.output = output;
    this.blocks = blocks;
    buffer = new byte[256];
    index = 0;
    bitsLeft = 8;
}
 
Example 26
Project: openjdk-jdk10   File: TopDownTest.java   Source Code and License 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 27
Project: OpenJSharp   File: FileImageOutputStreamSpi.java   Source Code and License 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 28
Project: OpenJSharp   File: OutputStreamImageOutputStreamSpi.java   Source Code and License 5 votes vote down vote up
public ImageOutputStream createOutputStreamInstance(Object output,
                                                    boolean useCache,
                                                    File cacheDir)
    throws IOException {
    if (output instanceof OutputStream) {
        OutputStream os = (OutputStream)output;
        if (useCache) {
            return new FileCacheImageOutputStream(os, cacheDir);
        } else {
            return new MemoryCacheImageOutputStream(os);
        }
    } else {
        throw new IllegalArgumentException();
    }
}
 
Example 29
Project: openjdk-jdk10   File: PNGImageWriter.java   Source Code and License 5 votes vote down vote up
IDATOutputStream(ImageOutputStream stream, int chunkLength,
                        int deflaterLevel) throws IOException
{
    this.stream = stream;
    this.chunkLength = chunkLength;
    this.def = new Deflater(deflaterLevel);

    startChunk();
}
 
Example 30
Project: openjdk-jdk10   File: SetOutput.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    ImageWriter iw = new PNGImageWriter(null);
    File f = File.createTempFile("imageio", "tmp");
    ImageOutputStream ios = ImageIO.createImageOutputStream(f);
    try {
        iw.setOutput(ios);
    } catch (NullPointerException npe) {
        f.delete();
        throw new RuntimeException("Got NullPointerException!");
    }
    f.delete();
}
 
Example 31
Project: openjdk-jdk10   File: MergeTreeTest.java   Source Code and License 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 32
Project: openjdk-jdk10   File: RGBImageTest.java   Source Code and License 5 votes vote down vote up
protected void doTest() throws IOException {
    BufferedImage biSrc = getSrc();

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
    writer.setOutput(ios);

    ImageWriteParam writeParam = writer.getDefaultWriteParam();
    IIOMetadata imageMetadata =
        writer.getDefaultImageMetadata(new ImageTypeSpecifier(biSrc), writeParam);

    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(writeParam);

    IIOImage iioImg = new IIOImage(biSrc, null, imageMetadata);
    writer.write(streamMetadata, iioImg, writeParam);
    ios.close();

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ImageInputStream iis = ImageIO.createImageInputStream(bais);
    ImageReader reader = ImageIO.getImageReader(writer);
    reader.setInput(iis);
    BufferedImage dst = reader.read(0);

    // do test
    int x = dx / 2;
    int y = height / 2;

    for (int i = 0; i < usedColors.length; i++) {
        int dstRgb = dst.getRGB(x, y);
        System.out.println("dstColor: " + Integer.toHexString(dstRgb));
        int srcRgb = usedColors[i].getRGB();
        System.out.println("srcColor: " + Integer.toHexString(srcRgb));
        if (dstRgb != srcRgb) {
            throw new RuntimeException("wrong color " + i + ": " + Integer.toHexString(dstRgb));
        }
        x += dx;
    }

}
 
Example 33
Project: OpenJSharp   File: JPEGImageWriter.java   Source Code and License 5 votes vote down vote up
public void setOutput(Object output) {
    setThreadLock();
    try {
        cbLock.check();

        super.setOutput(output); // validates output
        resetInternalState();
        ios = (ImageOutputStream) output; // so this will always work
        // Set the native destination
        setDest(structPointer);
    } finally {
        clearThreadLock();
    }
}
 
Example 34
Project: OpenJSharp   File: JFIFMarkerSegment.java   Source Code and License 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 35
Project: OpenJSharp   File: JFIFMarkerSegment.java   Source Code and License 5 votes vote down vote up
void writeThumbnailData(ImageOutputStream ios,
                        int [] thumbData,
                        JPEGImageWriter writer) throws IOException {
    int progInterval = thumbData.length / 20;  // approx. every 5%
    if (progInterval == 0) {
        progInterval = 1;
    }
    for (int i = 0; i < thumbData.length; i++) {
        ios.write(thumbData[i]);
        if ((i > progInterval) && (i % progInterval == 0)) {
            writer.thumbnailProgress
                (((float) i * 100) / ((float) thumbData.length));
        }
    }
}
 
Example 36
Project: jdk8u-jdk   File: WBMPImageWriterSpi.java   Source Code and License 5 votes vote down vote up
public WBMPImageWriterSpi() {
    super("Oracle Corporation",
          "1.0",
          formatNames,
          entensions,
          mimeType,
          "com.sun.imageio.plugins.wbmp.WBMPImageWriter",
          new Class[] { ImageOutputStream.class },
          readerSpiNames,
          true,
          null, null, null, null,
          true,
          null, null, null, null);
}
 
Example 37
Project: OpenJSharp   File: JFIFMarkerSegment.java   Source Code and License 5 votes vote down vote up
void write(ImageOutputStream ios,
           JPEGImageWriter writer) throws IOException {
    length = LENGTH_SIZE + DATA_SIZE + thumb.getLength();
    writeTag(ios);
    byte [] id = {0x4A, 0x46, 0x58, 0x58, 0x00};
    ios.write(id);
    ios.write(code);
    thumb.write(ios, writer);
}
 
Example 38
Project: openjdk-jdk10   File: BMPImageWriter.java   Source Code and License 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("BMPImageWriter0"));
        this.stream = (ImageOutputStream)output;
        stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
    } else
        this.stream = null;
}
 
Example 39
Project: OpenJSharp   File: JFIFMarkerSegment.java   Source Code and License 5 votes vote down vote up
void write(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);
    ios.write(thumbWidth);
    ios.write(thumbHeight);
}
 
Example 40
Project: jdk8u-jdk   File: ImageIO.java   Source Code and License 5 votes vote down vote up
/**
 * Writes image to output stream  using given image writer.
 */
private static boolean doWrite(RenderedImage im, ImageWriter writer,
                             ImageOutputStream output) throws IOException {
    if (writer == null) {
        return false;
    }
    writer.setOutput(output);
    try {
        writer.write(im);
    } finally {
        writer.dispose();
        output.flush();
    }
    return true;
}