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; }
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); }
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); } }
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(); }
/** * 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; } }
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); }
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."); } }
/** * 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(); }
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 ); }
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); } }
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 ); }
/** * 根据质量压缩图片,不改变图片的尺寸 * * @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); } }
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); }
/** * @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); }
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(); }
@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()); }
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"); }
@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; } }
/** * 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); } }
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!"); } }
public BitFile(ImageOutputStream output, boolean blocks) { this.output = output; this.blocks = blocks; buffer = new byte[256]; index = 0; bitsLeft = 8; }
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); }
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(); } }
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(); } }
IDATOutputStream(ImageOutputStream stream, int chunkLength, int deflaterLevel) throws IOException { this.stream = stream; this.chunkLength = chunkLength; this.def = new Deflater(deflaterLevel); startChunk(); }
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(); }
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"); } }
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; } }
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(); } }
/** * 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(); } }
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)); } } }
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); }
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); }
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; }
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); }
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."); } }
/** * 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; }
/** * 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> containing 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; ImageWriter writer = getWriter(im, formatName); if (writer == null) { /* Do not make changes in the file system if we have * no appropriate writer. */ return false; } try { output.delete(); stream = createImageOutputStream(output); } catch (IOException e) { throw new IIOException("Can't create output stream!", e); } try { return doWrite(im, writer, stream); } finally { stream.close(); } }