List of usage examples for javax.imageio.stream FileImageOutputStream FileImageOutputStream
public FileImageOutputStream(RandomAccessFile raf)
From source file:org.photovault.imginfo.CreateCopyImageCommand.java
/** Helper function to save a rendered image to file @param instanceFile The file into which the image will be saved @param img Image that willb e saved/*from w w w.j ava 2s . c o m*/ @param xmpData XPM metadata packet that should be saved with the image @throws PhotovaultException if saving does not succeed */ protected void saveImage(File instanceFile, RenderedImage img, byte[] xmpData) throws PhotovaultException { ImageOutputStream out = null; log.debug("Entry: saveImage, file = " + instanceFile.getAbsolutePath()); try { out = new FileImageOutputStream(instanceFile); } catch (IOException e) { log.error("Error writing image: " + e.getMessage()); throw new PhotovaultException(e.getMessage()); } if (img.getSampleModel().getSampleSize(0) == 16) { log.debug("16 bit image, converting to 8 bits"); double[] subtract = new double[1]; subtract[0] = 0; double[] divide = new double[1]; divide[0] = 1. / 256.; // Now we can rescale the pixels gray levels: ParameterBlock pbRescale = new ParameterBlock(); pbRescale.add(divide); pbRescale.add(subtract); pbRescale.addSource(img); PlanarImage outputImage = (PlanarImage) JAI.create("rescale", pbRescale, null); // Make sure it is a byte image - force conversion. ParameterBlock pbConvert = new ParameterBlock(); pbConvert.addSource(outputImage); pbConvert.add(DataBuffer.TYPE_BYTE); img = JAI.create("format", pbConvert); } IIOImage iioimg = new IIOImage(img, null, null); /* Not all encoders support metadata handling */ Iterator writers = ImageIO.getImageWritersByFormatName("jpeg"); ImageWriter imgwriter = null; while (writers.hasNext()) { imgwriter = (ImageWriter) writers.next(); if (imgwriter.getClass().getName().endsWith("JPEGImageEncoder")) { // Break on finding the core provider. break; } } if (imgwriter == null) { System.err.println("Cannot find core JPEG writer!"); } imgwriter.addIIOWriteWarningListener(new IIOWriteWarningListener() { public void warningOccurred(ImageWriter arg0, int arg1, String arg2) { log.warn("Warning from ImageWriter: " + arg2); } }); ImageWriteParam params = imgwriter.getDefaultWriteParam(); ImageTypeSpecifier its = ImageTypeSpecifier.createFromRenderedImage(img); IIOMetadata metadata = imgwriter.getDefaultImageMetadata(its, null); IIOMetadataNode metatop = (IIOMetadataNode) metadata.getAsTree("javax_imageio_jpeg_image_1.0"); NodeList markerSeqNodes = metatop.getElementsByTagName("markerSequence"); if (markerSeqNodes.getLength() > 0) { IIOMetadataNode xmpNode = new IIOMetadataNode("unknown"); xmpNode.setAttribute("MarkerTag", "225"); xmpNode.setUserObject(xmpData); markerSeqNodes.item(0).appendChild(xmpNode); } try { metadata.setFromTree("javax_imageio_jpeg_image_1.0", metatop); } catch (Exception e) { log.warn("error editing metadata: " + e.getMessage()); e.printStackTrace(); throw new PhotovaultException("error setting image metadata: \n" + e.getMessage()); } iioimg.setMetadata(metadata); try { imgwriter.setOutput(out); imgwriter.write(iioimg); } catch (IOException e) { log.warn("Exception while encoding" + e.getMessage()); throw new PhotovaultException( "Error writing instance " + instanceFile.getAbsolutePath() + ": " + e.getMessage()); } finally { try { out.close(); } catch (IOException e) { log.warn("Exception while closing file: " + e.getMessage()); imgwriter.dispose(); throw new PhotovaultException( "Error writing instance " + instanceFile.getAbsolutePath() + ": " + e.getMessage()); } imgwriter.dispose(); } log.debug("Exit: saveImage"); }
From source file:org.psystems.dicomweb.Dcm2Dcm.java
/** * Recodes the images from the source transfer syntax, as read from the src * file, to the specified destination syntax. */// w w w . j ava2 s .com public void recodeImages(File src, File dest) throws IOException { ImageReader reader = new DicomImageReaderSpi().createReaderInstance(); ImageWriter writer = new DicomImageWriterSpi().createWriterInstance(); FileImageInputStream input = new FileImageInputStream(src); reader.setInput(input); if (dest.exists()) dest.delete(); FileImageOutputStream output = new FileImageOutputStream(dest); writer.setOutput(output); DicomStreamMetaData streamMeta = (DicomStreamMetaData) reader.getStreamMetadata(); DicomObject ds = streamMeta.getDicomObject(); DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null); DicomObject newDs = new BasicDicomObject(); ds.copyTo(newDs); writeMeta.setDicomObject(newDs); int frames = ds.getInt(Tag.NumberOfFrames, 1); LookupTable lut = prepareBitStrip(writeMeta, reader); newDs.putString(Tag.TransferSyntaxUID, VR.UI, destinationSyntax.uid()); if (overwriteObject != null) { overwriteObject.copyTo(newDs); } writer.prepareWriteSequence(writeMeta); for (int i = 0; i < frames; i++) { WritableRaster r = (WritableRaster) reader.readRaster(i, null); ColorModel cm = ColorModelFactory.createColorModel(ds); BufferedImage bi = new BufferedImage(cm, r, false, null); if (lut != null) { lut.lookup(bi.getRaster(), bi.getRaster()); } IIOImage iioimage = new IIOImage(bi, null, null); writer.writeToSequence(iioimage, null); } writer.endWriteSequence(); output.close(); input.close(); }
From source file:org.psystems.dicomweb.Dcm2DcmCopy.java
/** * Recodes the images from the source transfer syntax, as read from the src * file, to the specified destination syntax. *///from w ww . j a v a 2s.c om public void recodeImages(File src, File dest) throws IOException { ImageReader reader = new DicomImageReaderSpi().createReaderInstance(); ImageWriter writer = new DicomImageWriterSpi().createWriterInstance(); FileImageInputStream input = new FileImageInputStream(src); reader.setInput(input); if (dest.exists()) dest.delete(); FileImageOutputStream output = new FileImageOutputStream(dest); writer.setOutput(output); DicomStreamMetaData streamMeta = (DicomStreamMetaData) reader.getStreamMetadata(); DicomObject ds = streamMeta.getDicomObject(); DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null); DicomObject newDs = new BasicDicomObject(); ds.copyTo(newDs); writeMeta.setDicomObject(newDs); int frames = ds.getInt(Tag.NumberOfFrames, 1); LookupTable lut = prepareBitStrip(writeMeta, reader); newDs.putString(Tag.TransferSyntaxUID, VR.UI, destinationSyntax.uid()); if (overwriteObject != null) { overwriteObject.copyTo(newDs); } writer.prepareWriteSequence(writeMeta); for (int i = 0; i < frames; i++) { WritableRaster r = (WritableRaster) reader.readRaster(i, null); ColorModel cm = ColorModelFactory.createColorModel(ds); BufferedImage bi = new BufferedImage(cm, r, false, null); if (lut != null) { lut.lookup(bi.getRaster(), bi.getRaster()); } IIOImage iioimage = new IIOImage(bi, null, null); writer.writeToSequence(iioimage, null); } writer.endWriteSequence(); output.close(); input.close(); }
From source file:org.tinymediamanager.core.ImageCache.java
/** * Cache image.// w w w. jav a 2 s .co m * * @param mf * the media file * @return the file the cached file * @throws Exception */ public static Path cacheImage(Path originalFile) throws Exception { MediaFile mf = new MediaFile(originalFile); Path cachedFile = ImageCache.getCacheDir() .resolve(getMD5(originalFile.toString()) + "." + Utils.getExtension(originalFile)); if (!Files.exists(cachedFile)) { // check if the original file exists && size > 0 if (!Files.exists(originalFile)) { throw new FileNotFoundException("unable to cache file: " + originalFile + "; file does not exist"); } if (Files.size(originalFile) == 0) { throw new EmptyFileException(originalFile); } // recreate cache dir if needed // rescale & cache BufferedImage originalImage = null; try { originalImage = createImage(originalFile); } catch (Exception e) { throw new Exception("cannot create image - file seems not to be valid? " + originalFile); } // calculate width based on MF type int desiredWidth = originalImage.getWidth(); // initialize with fallback switch (mf.getType()) { case FANART: if (originalImage.getWidth() > 1000) { desiredWidth = 1000; } break; case POSTER: if (originalImage.getHeight() > 500) { desiredWidth = 350; } break; case EXTRAFANART: case THUMB: case BANNER: case GRAPHIC: desiredWidth = 300; break; default: break; } // special handling for movieset-fanart or movieset-poster if (mf.getFilename().startsWith("movieset-fanart") || mf.getFilename().startsWith("movieset-poster")) { if (originalImage.getWidth() > 1000) { desiredWidth = 1000; } } Point size = calculateSize(desiredWidth, (int) (originalImage.getHeight() / 1.5), originalImage.getWidth(), originalImage.getHeight(), true); BufferedImage scaledImage = null; if (Globals.settings.getImageCacheType() == CacheType.FAST) { // scale fast scaledImage = Scalr.resize(originalImage, Scalr.Method.BALANCED, Scalr.Mode.FIT_EXACT, size.x, size.y); } else { // scale with good quality scaledImage = Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.FIT_EXACT, size.x, size.y); } originalImage = null; ImageWriter imgWrtr = null; ImageWriteParam imgWrtrPrm = null; // here we have two different ways to create our thumb // a) a scaled down jpg/png (without transparency) which we have to modify since OpenJDK cannot call native jpg encoders // b) a scaled down png (with transparency) which we can store without any more modifying as png if (hasTransparentPixels(scaledImage)) { // transparent image -> png imgWrtr = ImageIO.getImageWritersByFormatName("png").next(); imgWrtrPrm = imgWrtr.getDefaultWriteParam(); } else { // non transparent image -> jpg // convert to rgb BufferedImage rgb = new BufferedImage(scaledImage.getWidth(), scaledImage.getHeight(), BufferedImage.TYPE_INT_RGB); ColorConvertOp xformOp = new ColorConvertOp(null); xformOp.filter(scaledImage, rgb); imgWrtr = ImageIO.getImageWritersByFormatName("jpg").next(); imgWrtrPrm = imgWrtr.getDefaultWriteParam(); imgWrtrPrm.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT); imgWrtrPrm.setCompressionQuality(0.80f); scaledImage = rgb; } FileImageOutputStream output = new FileImageOutputStream(cachedFile.toFile()); imgWrtr.setOutput(output); IIOImage image = new IIOImage(scaledImage, null, null); imgWrtr.write(null, image, imgWrtrPrm); imgWrtr.dispose(); output.flush(); output.close(); scaledImage = null; } if (!Files.exists(cachedFile)) { throw new Exception("unable to cache file: " + originalFile); } return cachedFile; }
From source file:org.tros.logo.swing.LogoMenuBar.java
/** * Create an animated GIF./*from w ww.java 2s . c o m*/ * * @param p * @param canvas * @param filename * @throws UnsupportedEncodingException * @throws SVGGraphics2DIOException * @throws IOException */ private void generateGIF(final Drawable p, final BufferedImageProvider canvas, String filename) throws UnsupportedEncodingException, SVGGraphics2DIOException, IOException { final ImageOutputStream output = new FileImageOutputStream(new File(filename)); final GifSequenceWriter writer = new GifSequenceWriter(output, canvas.getBufferedImage().getType(), 1, true); final BufferedImage image = canvas.getBufferedImage(); final Graphics2D g2d = image.createGraphics(); DrawListener dl = new DrawListener() { @Override public void drawn(Drawable sender) { try { writer.writeToSequence(image); } catch (IOException ex) { } } }; p.addListener(dl); TurtleState ts = new TurtleState(); ts.width = image.getWidth(); ts.height = image.getHeight(); p.draw(g2d, ts); writer.close(); p.removeListener(dl); org.tros.utils.logging.Logging.getLogFactory().getLogger(LogoMenuBar.class) .info("{0} animation is complete!", filename); JOptionPane.showMessageDialog(parent, MessageFormat.format("{0} animation is complete!", filename), "Animated GIF Sequence Complete", JOptionPane.INFORMATION_MESSAGE); }
From source file:pl.edu.icm.visnow.lib.utils.ImageUtilities.java
public static void writeJpeg(BufferedImage img, float quality, File file) throws IOException { if (img == null) { return;/*from w ww. j ava2s .c om*/ } float q = quality; if (q < 0) { q = 0; } if (q > 1) { q = 1; } Iterator iter = ImageIO.getImageWritersByFormatName("jpeg"); ImageWriter writer = (ImageWriter) iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(q); // float between 0 and 1 // 1 specifies minimum compression and maximum quality FileImageOutputStream output = new FileImageOutputStream(file); writer.setOutput(output); IIOImage image = new IIOImage(img, null, null); writer.write(null, image, iwp); writer.dispose(); }