List of usage examples for javax.imageio ImageWriter write
public abstract void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException;
From source file:org.eclipse.birt.chart.device.svg.SVGImage.java
public SVGImage(Image image, URL url, byte[] data) { super();// ww w .jav a 2s.c om this.image = image; this.url = url; this.data = data; if (url == null && data == null && image instanceof BufferedImage) { ImageWriter iw = ImageWriterFactory.instance().createImageWriter("png", "html"); //$NON-NLS-1$ //$NON-NLS-2$ try { ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); ImageOutputStream ios = SecurityUtil.newImageOutputStream(baos); ImageWriteParam iwp = iw.getDefaultWriteParam(); iw.setOutput(ios); iw.write((IIOMetadata) null, new IIOImage((BufferedImage) image, null, null), iwp); ios.close(); this.data = baos.toByteArray(); baos.close(); } catch (IOException e) { // do nothing } finally { iw.dispose(); } } }
From source file:io.warp10.script.processing.Pencode.java
@Override public Object apply(WarpScriptStack stack) throws WarpScriptException { Object top = stack.pop();//from w ww . j a v a2s .c o m if (!(top instanceof processing.core.PGraphics)) { throw new WarpScriptException(getName() + " operates on a PGraphics instance."); } processing.core.PGraphics pg = (processing.core.PGraphics) top; pg.endDraw(); BufferedImage bimage = new BufferedImage(pg.pixelWidth, pg.pixelHeight, BufferedImage.TYPE_INT_ARGB); bimage.setRGB(0, 0, pg.pixelWidth, pg.pixelHeight, pg.pixels, 0, pg.pixelWidth); Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("png"); ImageWriter writer = null; if (iter.hasNext()) { writer = iter.next(); } ImageWriteParam param = writer.getDefaultWriteParam(); IIOMetadata metadata = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream output = new BufferedOutputStream(baos); try { writer.setOutput(ImageIO.createImageOutputStream(output)); writer.write(metadata, new IIOImage(bimage, null, metadata), param); } catch (IOException ioe) { throw new WarpScriptException(getName() + " error while encoding PGraphics.", ioe); } writer.dispose(); StringBuilder sb = new StringBuilder("data:image/png;base64,"); sb.append(Base64.encodeBase64String(baos.toByteArray())); stack.push(sb.toString()); // // Re-issue a 'beginDraw' so we can continue using the PGraphics instance // pg.beginDraw(); return stack; }
From source file:org.onehippo.forge.gallerymagick.core.command.ScalrProcessorUtils.java
/** * Resize the given image {@code sourceFile} with resizing it to {@code width} and {@code height} * and store the resized image to {@code targetFile}, with appending {@code extraOptions} in the command line if provided. * @param sourceFile source image file//from w w w . j ava 2 s . c o m * @param targetFile target image file * @param dimension image dimension * @param extraOptions extra command line options * @throws IOException if IO exception occurs */ public static void resizeImage(File sourceFile, File targetFile, ImageDimension dimension, String... extraOptions) throws IOException { if (dimension == null) { throw new IllegalArgumentException("Invalid dimension: " + dimension); } ImageReader reader = null; ImageWriter writer = null; try { reader = getImageReader(sourceFile); if (reader == null) { throw new IllegalArgumentException( "Unsupported image file name extension for reading: " + sourceFile); } writer = getImageWriter(targetFile); if (writer == null) { throw new IllegalArgumentException( "Unsupported image file name extension for writing: " + targetFile); } BufferedImage sourceImage = reader.read(0); BufferedImage resizedImage = Scalr.resize(sourceImage, Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC, dimension.getWidth(), dimension.getHeight()); final ImageWriteParam writeParam = writer.getDefaultWriteParam(); if (writeParam.canWriteCompressed()) { String[] compressionTypes = writeParam.getCompressionTypes(); if (compressionTypes != null && compressionTypes.length > 0) { writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); writeParam.setCompressionType(compressionTypes[0]); writeParam.setCompressionQuality(1.0f); } } final IIOImage iioImage = new IIOImage(resizedImage, null, null); writer.write(null, iioImage, writeParam); } finally { if (reader != null) { reader.dispose(); } if (writer != null) { writer.dispose(); } } }
From source file:org.egov.works.abstractestimate.service.EstimatePhotographService.java
public File compressImage(final MultipartFile[] files) throws IOException, FileNotFoundException { final BufferedImage image = ImageIO.read(files[0].getInputStream()); final File compressedImageFile = new File(files[0].getOriginalFilename()); final OutputStream os = new FileOutputStream(compressedImageFile); String fileExtenstion = files[0].getOriginalFilename(); fileExtenstion = fileExtenstion.substring(fileExtenstion.lastIndexOf(".") + 1); final Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(fileExtenstion); final ImageWriter writer = writers.next(); final ImageOutputStream ios = ImageIO.createImageOutputStream(os); writer.setOutput(ios);//from w w w . j av a 2 s. co m final ImageWriteParam param = writer.getDefaultWriteParam(); if (!fileExtenstion.equalsIgnoreCase("png")) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(0.5f); } writer.write(null, new IIOImage(image, null, null), param); os.close(); ios.close(); writer.dispose(); return compressedImageFile; }
From source file:org.gallery.web.controller.ImageController.java
public static boolean compressImg(BufferedImage src, File outfile, double d) { FileOutputStream out = null;// w w w. j a v a 2 s.c om ImageWriter imgWrier; ImageWriteParam imgWriteParams; // ? jpg imgWrier = ImageIO.getImageWritersByFormatName("jpg").next(); imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null); // ??MODE_EXPLICIT imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT); // ?qality?0~1 imgWriteParams.setCompressionQuality((float) d); imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED); ColorModel colorModel = ColorModel.getRGBdefault(); // ? imgWriteParams.setDestinationType( new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16))); try { out = new FileOutputStream(outfile); imgWrier.reset(); // out?write, ImageOutputStream? // OutputStream imgWrier.setOutput(ImageIO.createImageOutputStream(out)); // write??? imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
From source file:de.inren.service.picture.PictureModificationServiceImpl.java
private void writeJpeg(BufferedImage image, File file, float quality) throws IOException { ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(quality);/* w ww .j av a2 s . com*/ FileImageOutputStream output = new FileImageOutputStream(file); writer.setOutput(output); writer.write(null, new IIOImage(image, null, null), iwp); }
From source file:org.mycore.iview2.frontend.MCRTileCombineServlet.java
/** * Transmits combined file or sends thumbnail. * Uses {@link HttpServletRequest#getAttribute(String)} to retrieve information generated by {@link #think(MCRServletJob)}. * <table>//from w w w . j a va 2 s . c o m * <caption>description of {@link HttpServletRequest} attributes</caption> * <tr><th>keyName</th><th>type</th><th>description</th></tr> * <tr><td>{@link #THUMBNAIL_KEY}</td><td>{@link File}</td><td>.iview2 File with all tiles in it</td></tr> * <tr><td>{@link #IMAGE_KEY}</td><td>{@link BufferedImage}</td> * <td>generated image if <code>zoomLevel != 0</code> and no implementation of {@link MCRFooterInterface} defined</td></tr> * </table> */ @Override protected void render(final MCRServletJob job, final Exception ex) throws Exception { if (job.getResponse().isCommitted()) { return; } if (ex != null) { throw ex; } //check for thumnail final File iviewFile = ((Path) job.getRequest().getAttribute(THUMBNAIL_KEY)).toFile(); final BufferedImage combinedImage = (BufferedImage) job.getRequest().getAttribute(IMAGE_KEY); if (iviewFile != null && combinedImage == null) { sendThumbnail(iviewFile, job.getResponse()); return; } //send combined image job.getResponse().setHeader("Cache-Control", "max-age=" + MCRTileServlet.MAX_AGE); job.getResponse().setContentType("image/jpeg"); job.getResponse().setDateHeader("Last-Modified", iviewFile.lastModified()); final Date expires = new Date(System.currentTimeMillis() + MCRTileServlet.MAX_AGE * 1000); LOGGER.info("Last-Modified: " + new Date(iviewFile.lastModified()) + ", expire on: " + expires); job.getResponse().setDateHeader("Expires", expires.getTime()); final ImageWriter curImgWriter = imageWriter.get(); try (ServletOutputStream sout = job.getResponse().getOutputStream(); ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(sout);) { curImgWriter.setOutput(imageOutputStream); final IIOImage iioImage = new IIOImage(combinedImage, null, null); curImgWriter.write(null, iioImage, imageWriteParam); } finally { curImgWriter.reset(); } }
From source file:jails.http.converter.BufferedImageHttpMessageConverter.java
public void write(BufferedImage image, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { if (contentType == null) { contentType = getDefaultContentType(); }/* w ww.ja va2s .c om*/ Assert.notNull(contentType, "Count not determine Content-Type, set one using the 'defaultContentType' property"); outputMessage.getHeaders().setContentType(contentType); ImageOutputStream imageOutputStream = null; ImageWriter imageWriter = null; try { imageOutputStream = createImageOutputStream(outputMessage.getBody()); Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByMIMEType(contentType.toString()); if (imageWriters.hasNext()) { imageWriter = imageWriters.next(); ImageWriteParam iwp = imageWriter.getDefaultWriteParam(); process(iwp); imageWriter.setOutput(imageOutputStream); imageWriter.write(null, new IIOImage(image, null, null), iwp); } else { throw new HttpMessageNotWritableException( "Could not find javax.imageio.ImageWriter for Content-Type [" + contentType + "]"); } } finally { if (imageWriter != null) { imageWriter.dispose(); } if (imageOutputStream != null) { try { imageOutputStream.close(); } catch (IOException ex) { // ignore } } } }
From source file:org.polymap.core.data.image.ImageEncodeProcessor.java
private void imageioEncodeJPEG(Image image, ChunkedResponseOutputStream out) throws IOException { // this code is from http://forums.sun.com/thread.jspa?threadID=5197061 ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next(); ImageWriteParam param = writer.getDefaultWriteParam(); param.setSourceBands(new int[] { 0, 1, 2 }); ColorModel cm = new DirectColorModel(24, 0x00ff0000, // Red 0x0000ff00, // Green 0x000000ff, // Blue 0x0); // Alpha param.setDestinationType(new ImageTypeSpecifier(cm, cm.createCompatibleSampleModel(1, 1))); ImageOutputStream imageOut = ImageIO.createImageOutputStream(out); writer.setOutput(imageOut);//from w w w . j a va2 s .co m writer.write(null, new IIOImage((RenderedImage) image, null, null), param); writer.dispose(); imageOut.close(); }
From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ImageUtils.java
/** * Returns the data of a {@link BufferedImage} as a binary output stream. If the image is <code>null</code>, * a stream of zero bytes is returned.//from w ww . j a v a 2 s. com * * @param writer the writer to use for writing the image data. * @param image the image to write. * @param compressionQuality a float between 0 and 1 that indicates the desired compression quality. Values lower than * 0 will be interpreted as 0, values higher than 1 will be interpreted as 1. * * @return an output stream with the data of the given image. * * @throws IOException when creating the binary output stream failed. */ public static ByteArrayOutputStream writeImage(ImageWriter writer, BufferedImage image, float compressionQuality) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); if (image != null) { ImageOutputStream ios = null; try { ios = ImageIO.createImageOutputStream(out); writer.setOutput(ios); // write compressed images with high quality final ImageWriteParam writeParam = writer.getDefaultWriteParam(); if (writeParam.canWriteCompressed()) { String[] compressionTypes = writeParam.getCompressionTypes(); if (compressionTypes != null && compressionTypes.length > 0) { writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); writeParam.setCompressionType(compressionTypes[0]); // ensure a compression quality between 0 and 1 float trimmedCompressionQuality = Math.max(compressionQuality, 0); trimmedCompressionQuality = Math.min(trimmedCompressionQuality, 1f); writeParam.setCompressionQuality(trimmedCompressionQuality); } } final IIOImage iioImage = new IIOImage(image, null, null); writer.write(null, iioImage, writeParam); ios.flush(); } finally { if (ios != null) { ios.close(); } } } return out; }