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(); }
public static byte[] toJPG(BufferedImage originalImage) throws IOException { BufferedImage image = removeAlpha(originalImage); ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next(); ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam(); jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); jpgWriteParam.setCompressionQuality(0.9f); try (final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final MemoryCacheImageOutputStream mcios = new MemoryCacheImageOutputStream(bos)) { jpgWriter.setOutput(mcios); IIOImage outputImage = new IIOImage(image, null, null); jpgWriter.write(null, outputImage, jpgWriteParam); jpgWriter.dispose(); bos.flush(); return bos.toByteArray(); } }
private byte[] toPng(BufferedImage img, Float compressionQuality) throws IOException { ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next(); ImageWriteParam writeParam = writer.getDefaultWriteParam(); if (compressionQuality != null) { writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); writeParam.setCompressionQuality(compressionQuality); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageOutputStream stream = new MemoryCacheImageOutputStream(baos); try { writer.setOutput(stream); writer.write(null, new IIOImage(img, null, null), writeParam); } finally { stream.close(); writer.dispose(); } return baos.toByteArray(); }
public static void writeJPG( BufferedImage bufferedImage, OutputStream outputStream, float quality) throws IOException { Iterator<ImageWriter> iterator = ImageIO.getImageWritersByFormatName("jpg"); ImageWriter imageWriter = iterator.next(); ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam(); imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); imageWriteParam.setCompressionQuality(quality); ImageOutputStream imageOutputStream = new MemoryCacheImageOutputStream(outputStream); imageWriter.setOutput(imageOutputStream); IIOImage iioimage = new IIOImage(bufferedImage, null, null); imageWriter.write(null, iioimage, imageWriteParam); imageOutputStream.flush(); }
public static void writeToFile(BufferedImage img, String filename) { try { FileOutputStream out = new FileOutputStream(new File(filename)); String extension = null; int i = filename.lastIndexOf('.'); if (i > 0) { extension = filename.substring(i + 1); } if (extension != null) { ImageIO.write(img, extension, new MemoryCacheImageOutputStream(out)); } } catch (Exception e) { Logging.logError(e); } }
public byte[] getBytes() { if (bytes != null) { return bytes; } if (buffer != null) { bytes = new byte[buffer.remaining()]; buffer.get(bytes); return bytes; } if (image != null) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(image, "jpg", new MemoryCacheImageOutputStream(bos)); bytes = bos.toByteArray(); return bytes; } catch (Exception e) { Logging.logError(e); } } // TODO image --to--> bytes return null; }
private byte[] getJPGBytes(BufferedImage image) { ByteArrayOutputStream outputStream = null; try { ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next(); ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam(); jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); jpgWriteParam.setCompressionQuality(1.0f); outputStream = new ByteArrayOutputStream(); jpgWriter.setOutput(new MemoryCacheImageOutputStream((outputStream))); IIOImage outputImage = new IIOImage(image, null, null); jpgWriter.write(null, outputImage, jpgWriteParam); jpgWriter.dispose(); outputStream.flush(); return outputStream.toByteArray(); } catch (Exception e) { throw new RuntimeException(e); } finally { closeOutputStream(outputStream); } }
@Override public MBFImage applySimulation(MBFImage input) { try { Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg"); ImageWriter writer = iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); float compressionFactor = this.randomFloatInRange(minCompression, maxCompression); iwp.setCompressionQuality(compressionFactor); ByteArrayOutputStream output = new ByteArrayOutputStream(); writer.setOutput(new MemoryCacheImageOutputStream(output)); IIOImage image = new IIOImage(ImageUtilities.createBufferedImage(input), null, null); writer.write(null, image, iwp); return ImageUtilities.readMBF(new ByteArrayInputStream(output.toByteArray())); } catch (IOException e) { throw new Error(e); } }
private static byte[] bufferedImageToJPEG(BufferedImage bufferedImage, float quality) throws Exception { ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next(); ImageWriteParam writeParam = writer.getDefaultWriteParam(); ColorModel colorModel = new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 0x000000ff); ImageTypeSpecifier imageTypeSpecifier = new ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(1, 1)/*ignored*/); writeParam.setDestinationType(imageTypeSpecifier); writeParam.setSourceBands(new int[] {0, 1, 2}); writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); writeParam.setCompressionQuality(quality); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); writer.setOutput(new MemoryCacheImageOutputStream(buffer)); IIOImage ioImage = new IIOImage(bufferedImage, null, null); writer.write(null, ioImage, writeParam); writer.dispose(); return buffer.toByteArray(); }
/** * Can change this to choose a better compression level as the default * * @param image * @param scaledImage * @return */ private static boolean writeTo(BufferedImage image, OutputStream 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 MemoryCacheImageOutputStream(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; } }
/** * Generates a mipmap and writes it to the specified output stream. * * @param sourceUrl URL string for the source image to be down-sampled. * * @param mipmapLevelDelta difference between the mipmap level of the source image and * the mipmap level for the generated image (should be positive). * * @param format format of the down-sampled image (e.g. {@link Utils#JPEG_FORMAT}) * * @param jpegQuality JPEG quality (0.0 <= x <= 1.0, only relevant for JPEG images). * * @param outputStream output stream for the down-sampled image. * * @throws IllegalArgumentException * if the source URL cannot be loaded or an invalid delta value is specified. * * @throws IOException * if the down-sampled image cannot be written. */ public static void generateMipmap(final String sourceUrl, final int mipmapLevelDelta, final String format, final Float jpegQuality, final OutputStream outputStream) throws IllegalArgumentException, IOException { final ImagePlus sourceImagePlus = Utils.openImagePlusUrl(sourceUrl); if (sourceImagePlus == null) { throw new IllegalArgumentException("failed to load '" + sourceUrl + "' for scaling"); } if (mipmapLevelDelta < 1) { throw new IllegalArgumentException("mipmap level delta value (" + mipmapLevelDelta + ") must be greater than 0"); } final ImageProcessor downSampledProcessor = Downsampler.downsampleImageProcessor(sourceImagePlus.getProcessor(), mipmapLevelDelta); final BufferedImage downSampledImage = downSampledProcessor.getBufferedImage(); final ImageOutputStream imageOutputStream = new MemoryCacheImageOutputStream(outputStream); Utils.writeImage(downSampledImage, format, false, jpegQuality, imageOutputStream); }
@Override public void write(final OutputStream outputStream) throws IOException, WebApplicationException { LOG.info("write: entry"); if (Utils.PNG_FORMAT.equals(format)) { writePngImage(targetImage, 6, FilterType.FILTER_PAETH, outputStream); } else if (Utils.TIFF_FORMAT.equals(format)) { Utils.writeTiffImage(targetImage, outputStream); } else { final ImageOutputStream imageOutputStream = new MemoryCacheImageOutputStream(outputStream); Utils.writeImage(targetImage, format, convertToGray, quality, imageOutputStream); } LOG.info("write: exit"); }
public void convert(Node node, LayoutContext ctx, OutputStream out) throws IOException { BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); JEuclidView view = new JEuclidView(node, ctx, graphics); int ascentHeight = (int) Math.ceil((double) view.getAscentHeight()); int descentHeight = (int) Math.ceil((double) view.getDescentHeight()); int height = ascentHeight + descentHeight; int width = (int) Math.ceil((double) view.getWidth()); image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); graphics = image.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); view.draw(graphics, 0.0F, (float) ascentHeight); ImageOutputStream imageOutputStream = new MemoryCacheImageOutputStream(out); ImageWriter writer = getImageWriter(MimeType.PNG); writer.setOutput(imageOutputStream); writer.write(image); imageOutputStream.close(); }
/** * Writes an image to a servlet response * * @param response servlet response * @param image image bytes * @throws IOException */ @SuppressWarnings("squid:S1166") // Exception caught and handled public static void writeImageToResponse(HttpServletResponse response, byte[] image) throws IOException { try { ImageOutputStream imageStream = new MemoryCacheImageOutputStream(response.getOutputStream()); imageStream.write(image, 0, image.length); response.setContentLength((int) imageStream.length()); imageStream.close(); } // TODO: remove these catches - This is to prevent seeing the broken pipes exception // over and over again in the trace...leave catch in until issue is fixed (#1122) catch (IIOException | IndexOutOfBoundsException ignored) { } }
@Override public void write(Image image, OutputStream out) throws IOException { javax.imageio.ImageWriter writer = ImageIO.getImageWritersByFormatName("gif").next(); ImageWriteParam params = writer.getDefaultWriteParam(); if (progressive) { params.setProgressiveMode(ImageWriteParam.MODE_DEFAULT); } else { params.setProgressiveMode(ImageWriteParam.MODE_DISABLED); } try (MemoryCacheImageOutputStream output = new MemoryCacheImageOutputStream(out)) { writer.setOutput(output); writer.write(null, new IIOImage(image.awt(), null, null), params); writer.dispose(); } IOUtils.closeQuietly(out); }
@Test public void timeCLibEncode() throws Exception { ImageWriter writer = new CLibPNGImageWriterSpi().createWriterInstance(); ImageWriteParam iwp = writer.getDefaultWriteParam(); // Define compression mode iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // best compression // iwp.setCompressionType("FILTERED"); // we can control quality here iwp.setCompressionQuality(0.75f); // destination image type iwp.setDestinationType(new ImageTypeSpecifier(image.getColorModel(), image.getSampleModel())); ByteArrayOutputStream bos = new ByteArrayOutputStream(); MemoryCacheImageOutputStream mos = new MemoryCacheImageOutputStream(bos); writer.setOutput(mos); writer.write(null, new IIOImage(image, null, null), iwp); mos.flush(); collectPng("clib", bos.toByteArray()); // System.out.println(bos.size()); }
@Test public void timeCLibEncode() throws Exception { ImageWriter writer = new CLibPNGImageWriterSpi().createWriterInstance(); ImageWriteParam iwp = writer.getDefaultWriteParam(); // Define compression mode iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // best compression // iwp.setCompressionType("FILTERED"); // we can control quality here iwp.setCompressionQuality((1 - compression / 9f)); // destination image type iwp.setDestinationType(new ImageTypeSpecifier(image.getColorModel(), image.getSampleModel())); ByteArrayOutputStream bos = new ByteArrayOutputStream(); MemoryCacheImageOutputStream mos = new MemoryCacheImageOutputStream(bos); writer.setOutput(mos); writer.write(null, new IIOImage(image, null, null), iwp); mos.flush(); collectPng("clib", bos.toByteArray()); // System.out.println(bos.size()); }
@Override public BufferedImage apply(BufferedImage img) { if(compressionLevel == 0f) return img; try { ImageWriter iw = ImageIO.getImageWritersByFormatName("jpeg").next(); JPEGImageWriteParam iwp = (JPEGImageWriteParam) iw.getDefaultWriteParam(); iwp.setOptimizeHuffmanTables(false); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setProgressiveMode(ImageWriteParam.MODE_DISABLED); iwp.setCompressionQuality(1f-compressionLevel); ByteArrayOutputStream baos = new ByteArrayOutputStream(); iw.setOutput(new MemoryCacheImageOutputStream(baos)); IIOImage outputImage = new IIOImage(img, null, null); iw.write(null, outputImage, iwp); iw.dispose(); baos.flush(); byte[] returnImage = baos.toByteArray(); baos.close(); BufferedImage img2 = ImageIO.read(new ByteArrayInputStream(returnImage)); if(img2 == null) throw new Exception(); else img = img2; } catch (Exception e) { e.printStackTrace(); } return img; }
private ImageOutputStream createImageOutputStream(OutputStream os) throws IOException { if (this.cacheDir != null) { return new FileCacheImageOutputStream(os, this.cacheDir); } else { return new MemoryCacheImageOutputStream(os); } }
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(); } }
public static void main(String[] args) throws IOException { OutputStream ostream = new ByteArrayOutputStream(); FileCacheImageOutputStream fcios = new FileCacheImageOutputStream(ostream, null); test(fcios); MemoryCacheImageOutputStream mcios = new MemoryCacheImageOutputStream(ostream); test(mcios); }
@Override protected void writeFrame(OutputStream out, BufferedImage image, Map<String, Object> settings) throws IOException { if(image.getType()==BufferedImage.TYPE_INT_ARGB || image.getType()==BufferedImage.TYPE_INT_ARGB_PRE) { if(printWarning==false) { printWarning = true; System.err.println("JPEGMovWriter Warning: a BufferedImage of type TYPE_INT_ARGB may produce unexpected results. The recommended type is TYPE_INT_RGB."); } } float quality; if(settings!=null && settings.get(PROPERTY_QUALITY) instanceof Number) { quality = ((Number)settings.get(PROPERTY_QUALITY)).floatValue(); } else if(settings!=null && settings.get(PROPERTY_QUALITY) instanceof String) { quality = Float.parseFloat((String)settings.get(PROPERTY_QUALITY)); } else { quality = defaultQuality; } MemoryCacheImageOutputStream iOut = new MemoryCacheImageOutputStream(out); ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/jpeg").next(); ImageWriteParam iwParam = iw.getDefaultWriteParam(); iwParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwParam.setCompressionQuality(quality); iw.setOutput(iOut); IIOImage img = new IIOImage(image, null, null); iw.write(null, img, iwParam); }
/** * @param srcJpeg source jpeg to be optimized * @param configData used configuration * @return optimized jpeg with quality reduced to ConfigUtils.jpegQuality */ public static byte[] optimizedJpeg(byte[] srcJpeg, ConfigData configData) { try { Iterator iter = ImageIO.getImageWritersByFormatName("jpeg"); ImageWriter imgWriter = (ImageWriter)iter.next(); ImageWriteParam imgWriterParam = imgWriter.getDefaultWriteParam(); imgWriterParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); imgWriterParam.setCompressionQuality(configData.jpegQuality); ByteArrayOutputStream baos = new ByteArrayOutputStream(srcJpeg.length); MemoryCacheImageOutputStream mcios = new MemoryCacheImageOutputStream(baos); imgWriter.setOutput(mcios); ByteArrayInputStream bais = new ByteArrayInputStream(srcJpeg); BufferedImage origBufImage = ImageIO.read(bais); IIOImage origIioImage = new IIOImage(origBufImage, null, null); imgWriter.write(null, origIioImage, imgWriterParam); imgWriter.dispose(); byte[] dstJpeg = baos.toByteArray(); mcios.close(); baos.close(); return dstJpeg; } catch (IOException exc) { return srcJpeg; } }
public static void main(String[] args) throws Exception { try { LoggingFactory.getInstance().configure(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("object.data")); ImageIO.write(null, "jpg", new MemoryCacheImageOutputStream(out)); } catch (Exception e) { Logging.logError(e); } }
public static byte[] gifify(Collection<BufferedImage> imgs) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageOutputStream ios = new MemoryCacheImageOutputStream(baos); GifWriter gw = new GifWriter(ios, 500, "hello world"); imgs.forEach(gw::addImage); gw.close(); ios.flush(); return baos.toByteArray(); } catch (IOException e){ throw new RuntimeException(e); } }
/** * writeBinaryData() method * Writes results to a Binary file (4-byte float) */ static public void writeBinaryData() { FileOutputStream fos; BufferedOutputStream bos; try { fos = new FileOutputStream(outputVolume); bos = new BufferedOutputStream(fos); MemoryCacheImageOutputStream mcios = new MemoryCacheImageOutputStream(bos); // mcios.setByteOrder(java.nio.ByteOrder.LITTLE_ENDIAN); setByteOrder(mcios, byteorder); //for (int i=0; i < p_values.length; i++) //mcios.writeFloat((float)thresholdedPMap[i]); for (int i=0; i < resultsPValues.length; i++) mcios.writeFloat((float)resultsPValues[i]); System.out.println("Finished Writing out Binary Output\n" +"resultsPValues[0]="+resultsPValues[0] +"\t resultsPValues["+(resultsPValues.length/2)+"]=" +resultsPValues[resultsPValues.length/2]); mcios.flush(); mcios.close(); bos.flush(); bos.close(); fos.flush(); fos.close(); } catch (Exception e) { System.out.println("Error in writeBinaryData(): "+e); } return; }
/** * This method sets the Bite-Order for a MemoryCacheImageOutputStream * @param dis - MemoryCacheImageOutputStream * @param byteorder - String representation of byteorder. Options are * big (java.nio.ByteOrder.BIG_ENDIAN) * little (java.nio.ByteOrder.LITTLE_ENDIAN) * system (default system byteorder, java.nio.ByteOrder.nativeOrder()) */ public static void setByteOrder(MemoryCacheImageOutputStream dos, String byteorder) { if (byteorder.compareToIgnoreCase("little") == 0) { dos.setByteOrder(java.nio.ByteOrder.LITTLE_ENDIAN); } else if (byteorder.compareToIgnoreCase("big") == 0) { dos.setByteOrder(java.nio.ByteOrder.BIG_ENDIAN); } else { dos.setByteOrder(java.nio.ByteOrder.nativeOrder()); } return; }
/** * Creates a new CCITT group 4 (T6) compressed image XObject from a b/w BufferedImage. This compression technique * usually results in smaller images than those produced by * {@link LosslessFactory#createFromImage(PDDocument, BufferedImage) }. * * @param image the image. * @return a new image XObject. * @throws IOException if there is an error creating the image. * @throws IllegalArgumentException if the BufferedImage is not a b/w image. */ public static PDImageXObject createFromImage(BufferedImage image) throws IOException { if (image.getType() != BufferedImage.TYPE_BYTE_BINARY && image.getColorModel().getPixelSize() != 1) { throw new IllegalArgumentException("Only 1-bit b/w images supported"); } int height = image.getHeight(); int width = image.getWidth(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (MemoryCacheImageOutputStream mcios = new MemoryCacheImageOutputStream(bos)) { for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { // flip bit to avoid having to set /BlackIs1 mcios.writeBits(~(image.getRGB(x, y) & 1), 1); } if (mcios.getBitOffset() != 0) { mcios.writeBits(0, 8 - mcios.getBitOffset()); } } mcios.flush(); } return prepareImageXObject(bos.toByteArray(), width, height, PDDeviceGray.INSTANCE); }