Java Code Examples for java.awt.image.RenderedImage

The following are top voted examples for showing how to use java.awt.image.RenderedImage. 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: imageio-jnr   File: TurboJpegImageWriter.java   Source Code and License 7 votes vote down vote up
@Override
public void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
  RenderedImage img = image.getRenderedImage();
  if (stream == null) {
    throw new IOException("Set an output first!");
  }
  if (param == null) {
    param = getDefaultWriteParam();
  }
  Rectangle sourceRegion = new Rectangle(0, 0, img.getWidth(), img.getHeight());
  if (param.getSourceRegion() != null) {
    sourceRegion = sourceRegion.intersection(param.getSourceRegion());
  }
  Raster raster = img.getData(sourceRegion);
  int quality = 85;
  if (param.getCompressionMode() == ImageWriteParam.MODE_EXPLICIT) {
    quality = (int) (param.getCompressionQuality() * 100);
  }
  try {
    stream.write(lib.encode(raster, quality).array());
  } catch (TurboJpegException e) {
    throw new IOException(e);
  }
}
 
Example 2
Project: OpenJSharp   File: PNGImageWriter.java   Source Code and License 7 votes vote down vote up
private void write_IDAT(RenderedImage image) throws IOException {
    IDATOutputStream ios = new IDATOutputStream(stream, 32768);
    try {
        if (metadata.IHDR_interlaceMethod == 1) {
            for (int i = 0; i < 7; i++) {
                encodePass(ios, image,
                           PNGImageReader.adam7XOffset[i],
                           PNGImageReader.adam7YOffset[i],
                           PNGImageReader.adam7XSubsampling[i],
                           PNGImageReader.adam7YSubsampling[i]);
                if (abortRequested()) {
                    break;
                }
            }
        } else {
            encodePass(ios, image, 0, 0, 1, 1);
        }
    } finally {
        ios.finish();
    }
}
 
Example 3
Project: openjdk-jdk10   File: TIFFImageWriter.java   Source Code and License 6 votes vote down vote up
public void prepareInsertEmpty(int imageIndex,
                               ImageTypeSpecifier imageType,
                               int width,
                               int height,
                               IIOMetadata imageMetadata,
                               List<? extends BufferedImage> thumbnails,
                               ImageWriteParam param) throws IOException {
    checkParamsEmpty(imageType, width, height, thumbnails);

    this.isInsertingEmpty = true;

    SampleModel emptySM = imageType.getSampleModel();
    RenderedImage emptyImage =
        new EmptyImage(0, 0, width, height,
                       0, 0, emptySM.getWidth(), emptySM.getHeight(),
                       emptySM, imageType.getColorModel());

    insert(imageIndex, new IIOImage(emptyImage, null, imageMetadata),
           param, false);
}
 
Example 4
Project: 2D-Elliptic-Mesh-Generator   File: PlotCanvas.java   Source Code and License 6 votes vote down vote up
public void toGraphicFile(File file) throws IOException {

        Image image = createImage(getWidth(), getHeight());
        paint(image.getGraphics());
        image = new ImageIcon(image).getImage();

        BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics g = bufferedImage.createGraphics();
        g.drawImage(image, 0, 0, Color.WHITE, null);
        g.dispose();

        try {
            ImageIO.write((RenderedImage) bufferedImage, "PNG", file);
        } catch (IllegalArgumentException ex) {
        }
    }
 
Example 5
Project: 2D-Elliptic-Mesh-Generator   File: PlotPanel.java   Source Code and License 6 votes vote down vote up
public void toGraphicFile(File file) throws IOException {
    // otherwise toolbar appears
    plotToolBar.setVisible(false);

    Image image = createImage(getWidth(), getHeight());
    paint(image.getGraphics());
    image = new ImageIcon(image).getImage();

    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics g = bufferedImage.createGraphics();
    g.drawImage(image, 0, 0, Color.WHITE, null);
    g.dispose();

    // make it reappear
    plotToolBar.setVisible(true);

    try {
        ImageIO.write((RenderedImage) bufferedImage, "PNG", file);
    } catch (IllegalArgumentException ex) {
    }
}
 
Example 6
Project: OpenJSharp   File: PaletteBuilder.java   Source Code and License 6 votes vote down vote up
protected RenderedImage getIndexedImage() {
    IndexColorModel icm = getIndexColorModel();

    BufferedImage dst =
        new BufferedImage(src.getWidth(), src.getHeight(),
                          BufferedImage.TYPE_BYTE_INDEXED, icm);

    WritableRaster wr = dst.getRaster();
    for (int y =0; y < dst.getHeight(); y++) {
        for (int x = 0; x < dst.getWidth(); x++) {
            Color aColor = getSrcColor(x,y);
            wr.setSample(x, y, 0, findColorIndex(root, aColor));
        }
    }

    return dst;
}
 
Example 7
Project: OpenJSharp   File: ImageTypeSpecifier.java   Source Code and License 6 votes vote down vote up
/**
 * Returns an <code>ImageTypeSpecifier</code> that encodes the
 * layout of a <code>RenderedImage</code> (which may be a
 * <code>BufferedImage</code>).
 *
 * @param image a <code>RenderedImage</code>.
 *
 * @return an <code>ImageTypeSpecifier</code> with the desired
 * characteristics.
 *
 * @exception IllegalArgumentException if <code>image</code> is
 * <code>null</code>.
 */
public static
    ImageTypeSpecifier createFromRenderedImage(RenderedImage image) {
    if (image == null) {
        throw new IllegalArgumentException("image == null!");
    }

    if (image instanceof BufferedImage) {
        int bufferedImageType = ((BufferedImage)image).getType();
        if (bufferedImageType != BufferedImage.TYPE_CUSTOM) {
            return getSpecifier(bufferedImageType);
        }
    }

    return new ImageTypeSpecifier(image);
}
 
Example 8
Project: openjdk-jdk10   File: PNGImageWriter.java   Source Code and License 6 votes vote down vote up
private void write_IDAT(RenderedImage image, int deflaterLevel)
    throws IOException
{
    IDATOutputStream ios = new IDATOutputStream(stream, 32768,
                                                deflaterLevel);
    try {
        if (metadata.IHDR_interlaceMethod == 1) {
            for (int i = 0; i < 7; i++) {
                encodePass(ios, image,
                           PNGImageReader.adam7XOffset[i],
                           PNGImageReader.adam7YOffset[i],
                           PNGImageReader.adam7XSubsampling[i],
                           PNGImageReader.adam7YSubsampling[i]);
                if (abortRequested()) {
                    break;
                }
            }
        } else {
            encodePass(ios, image, 0, 0, 1, 1);
        }
    } finally {
        ios.finish();
    }
}
 
Example 9
Project: spring2017java   File: FXMLDocumentController.java   Source Code and License 6 votes vote down vote up
@FXML
private void handleFileSaveAction(ActionEvent event) {
    FileChooser fileChooser = new FileChooser();
    File file = fileChooser.showSaveDialog(null);
    
    if (file != null) {
        try {
            WritableImage writableImage = new WritableImage((int) drawingCanvas.getWidth(), (int) drawingCanvas.getHeight());
            drawingCanvas.snapshot(null, writableImage);
            RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);            
            ImageIO.write(renderedImage, "png", file);
        } catch (IOException ex) {
            Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
 
Example 10
Project: spring2017java   File: FXMLDocumentController.java   Source Code and License 6 votes vote down vote up
@FXML
private void handleFileSaveAction(ActionEvent event) {
    FileChooser fileChooser = new FileChooser();
    File file = fileChooser.showSaveDialog(null);
    System.out.println("Saving #" + file + "#");
    if (file != null) {
        // Stole the following part from:
        // http://java-buddy.blogspot.com/2013/04/save-canvas-to-png-file.html
        try {
            WritableImage writableImage = new WritableImage((int) drawingCanvas.getWidth(), (int) drawingCanvas.getHeight());
            drawingCanvas.snapshot(null, writableImage);
            RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
            // hometask: make sure you can save files in any format (not just png)
            // hints: find the extension of the file from the filename, then use substring
            ImageIO.write(renderedImage, "png", file);
        } catch (IOException ex) {
            System.err.println("Couldn't save the file!");
            // hometask: throw an alert dialog from here
        }
    }
}
 
Example 11
Project: openjdk-jdk10   File: PaletteBuilder.java   Source Code and License 6 votes vote down vote up
protected RenderedImage getIndexedImage() {
    IndexColorModel icm = getIndexColorModel();

    BufferedImage dst =
        new BufferedImage(src.getWidth(), src.getHeight(),
                          BufferedImage.TYPE_BYTE_INDEXED, icm);

    WritableRaster wr = dst.getRaster();
    for (int y =0; y < dst.getHeight(); y++) {
        for (int x = 0; x < dst.getWidth(); x++) {
            Color aColor = getSrcColor(x,y);
            wr.setSample(x, y, 0, findColorIndex(root, aColor));
        }
    }

    return dst;
}
 
Example 12
Project: jdk8u-jdk   File: PaletteBuilder.java   Source Code and License 6 votes vote down vote up
protected RenderedImage getIndexedImage() {
    IndexColorModel icm = getIndexColorModel();

    BufferedImage dst =
        new BufferedImage(src.getWidth(), src.getHeight(),
                          BufferedImage.TYPE_BYTE_INDEXED, icm);

    WritableRaster wr = dst.getRaster();
    for (int y =0; y < dst.getHeight(); y++) {
        for (int x = 0; x < dst.getWidth(); x++) {
            Color aColor = getSrcColor(x,y);
            wr.setSample(x, y, 0, findColorIndex(root, aColor));
        }
    }

    return dst;
}
 
Example 13
Project: jdk8u-jdk   File: PNGImageWriter.java   Source Code and License 6 votes vote down vote up
private void write_IDAT(RenderedImage image) throws IOException {
    IDATOutputStream ios = new IDATOutputStream(stream, 32768);
    try {
        if (metadata.IHDR_interlaceMethod == 1) {
            for (int i = 0; i < 7; i++) {
                encodePass(ios, image,
                           PNGImageReader.adam7XOffset[i],
                           PNGImageReader.adam7YOffset[i],
                           PNGImageReader.adam7XSubsampling[i],
                           PNGImageReader.adam7YSubsampling[i]);
                if (abortRequested()) {
                    break;
                }
            }
        } else {
            encodePass(ios, image, 0, 0, 1, 1);
        }
    } finally {
        ios.finish();
    }
}
 
Example 14
Project: openjdk-jdk10   File: GIFImageWriter.java   Source Code and License 5 votes vote down vote up
private boolean needToCreateIndex(RenderedImage image) {

        SampleModel sampleModel = image.getSampleModel();
        ColorModel colorModel = image.getColorModel();

        return sampleModel.getNumBands() != 1 ||
            sampleModel.getSampleSize()[0] > 8 ||
            colorModel.getComponentSize()[0] > 8;
    }
 
Example 15
Project: dhus-core   File: ProcessingUtils.java   Source Code and License 5 votes vote down vote up
public static RenderedImage resizeImage(RenderedImage image, int width, int height)
      throws InconsistentImageScale
{
   RenderedImage resizedImage=image;
   // Computes ratio and scale
   float scale=getScale(image.getWidth(),image.getHeight(),width,height);
   
   // Processing resize process
   ParameterBlock pb = new ParameterBlock();
   // The source image
   pb.addSource(resizedImage);
   // The xScale
   pb.add(scale);
   // The yScale
   pb.add(scale);
   // The x translation
   pb.add(0.0F);
   // The y translation
   pb.add(0.0F);
   // The interpolation
   pb.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC));
   resizedImage = JAI.create("scale", pb, null);
   
   LOGGER.debug("Image resized to : " + resizedImage.getWidth() + "x"
      + resizedImage.getHeight());
   
   return resizedImage;
}
 
Example 16
Project: Motunautr   File: FileIcon.java   Source Code and License 5 votes vote down vote up
public static RenderedImage toRenderedImage(final Image img) {
	if (img instanceof RenderedImage)
		return (RenderedImage) img;
	final int savedSize = 64;
	final BufferedImage b = new BufferedImage(savedSize, savedSize, BufferedImage.TYPE_INT_ARGB);
	final Graphics2D g = b.createGraphics();
	g.drawImage(img, 0, 0, savedSize, savedSize, null);
	g.dispose();
	return b;
}
 
Example 17
Project: ColorMOTD   File: MotdServerIcon.java   Source Code and License 5 votes vote down vote up
static String imageToDataString(RenderedImage image) {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {
        ImageIO.write(image, "png", bout);
    } catch (IOException e) {
        throw new UncheckedIOException("Not possible", e);
    }

    byte[] data = bout.toByteArray();
    byte[] base64 = Base64.getEncoder().encode(data);
    return "data:image/png;base64," + new String(base64, StandardCharsets.UTF_8);
}
 
Example 18
Project: openjdk-jdk10   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;
}
 
Example 19
Project: OpenJSharp   File: GIFImageWriter.java   Source Code and License 5 votes vote down vote up
private boolean needToCreateIndex(RenderedImage image) {

        SampleModel sampleModel = image.getSampleModel();
        ColorModel colorModel = image.getColorModel();

        return sampleModel.getNumBands() != 1 ||
            sampleModel.getSampleSize()[0] > 8 ||
            colorModel.getComponentSize()[0] > 8;
    }
 
Example 20
Project: OpenJSharp   File: GIFImageWriter.java   Source Code and License 5 votes vote down vote up
private void writeRows(RenderedImage image, LZWCompressor compressor,
                       int sx, int sdx, int sy, int sdy, int sw,
                       int dy, int ddy, int dw, int dh,
                       int numRowsWritten, int progressReportRowPeriod)
  throws IOException {
    if (DEBUG) System.out.println("Writing unoptimized");

    int[] sbuf = new int[sw];
    byte[] dbuf = new byte[dw];

    Raster raster =
        image.getNumXTiles() == 1 && image.getNumYTiles() == 1 ?
        image.getTile(0, 0) : image.getData();
    for (int y = dy; y < dh; y += ddy) {
        if (numRowsWritten % progressReportRowPeriod == 0) {
            if (abortRequested()) {
                processWriteAborted();
                return;
            }
            processImageProgress((numRowsWritten*100.0F)/dh);
        }

        raster.getSamples(sx, sy, sw, 1, 0, sbuf);
        for (int i = 0, j = 0; i < dw; i++, j += sdx) {
            dbuf[i] = (byte)sbuf[j];
        }
        compressor.compress(dbuf, 0, dw);
        numRowsWritten++;
        sy += sdy;
    }
}
 
Example 21
Project: geomapapp   File: SCSImage2.java   Source Code and License 5 votes vote down vote up
public void saveJPG(File outputFile, boolean saveWholeImage) throws IOException {
	Rectangle rect;
	if ( saveWholeImage ) {
		rect = this.getBounds();
	}
	else {
		rect = scrollPane.getViewport().getVisibleRect().getBounds();
	}
	BufferedImage im = new BufferedImage( rect.width, rect.height, BufferedImage.TYPE_INT_RGB);
	if ( saveWholeImage ) {
		im.getGraphics().setColor(Color.white);
		im.getGraphics().fillRect(rect.x, rect.y, rect.width, rect.height);
		this.paintWhole(im.getGraphics());
	}
	else {
		im.getGraphics().setColor(Color.white);
		im.getGraphics().fillRect(rect.x, rect.y, rect.width, rect.height);
		scrollPane.getViewport().paint(im.getGraphics());
	}
	int s_idx = outputFile.getName().indexOf(".");
	String suffix = s_idx<0
			? "jpg"
			: outputFile.getName().substring(s_idx+1);
	if( !javax.imageio.ImageIO.getImageWritersBySuffix(suffix).hasNext() ) {
		suffix = "jpg";
	}
	javax.imageio.ImageIO.write( (RenderedImage)im, suffix, outputFile );
}
 
Example 22
Project: OpenJSharp   File: ImageIO.java   Source Code and License 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example 23
Project: OpenJSharp   File: ImageIO.java   Source Code and License 5 votes vote down vote up
/**
 * Returns <code>ImageWriter</code> instance according to given
 * rendered image and image format or <code>null</code> if there
 * is no appropriate writer.
 */
private static ImageWriter getWriter(RenderedImage im,
                                     String formatName) {
    ImageTypeSpecifier type =
        ImageTypeSpecifier.createFromRenderedImage(im);
    Iterator<ImageWriter> iter = getImageWriters(type, formatName);

    if (iter.hasNext()) {
        return iter.next();
    } else {
        return null;
    }
}
 
Example 24
Project: openjdk-jdk10   File: ImageIO.java   Source Code and License 5 votes vote down vote up
/**
 * Returns {@code ImageWriter} instance according to given
 * rendered image and image format or {@code null} if there
 * is no appropriate writer.
 */
private static ImageWriter getWriter(RenderedImage im,
                                     String formatName) {
    ImageTypeSpecifier type =
        ImageTypeSpecifier.createFromRenderedImage(im);
    Iterator<ImageWriter> iter = getImageWriters(type, formatName);

    if (iter.hasNext()) {
        return iter.next();
    } else {
        return null;
    }
}
 
Example 25
Project: FlashLib   File: FlashFXUtils.java   Source Code and License 5 votes vote down vote up
public static Image bufferedImage2FxImage(BufferedImage img){
	ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ImageIO.write((RenderedImage) img, "jpg", out);
        out.flush();
       } catch (IOException ex) {
       }
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    return new Image(in);
}
 
Example 26
Project: openjdk-jdk10   File: ImageIO.java   Source Code and License 5 votes vote down vote up
/**
 * Writes an image using an arbitrary {@code ImageWriter}
 * that supports the given format to a {@code File}.  If
 * there is already a {@code File} present, its contents are
 * discarded.
 *
 * @param im a {@code RenderedImage} to be written.
 * @param formatName a {@code String} containing the informal
 * name of the format.
 * @param output a {@code File} to be written to.
 *
 * @return {@code false} if no appropriate writer is found.
 *
 * @exception IllegalArgumentException if any parameter is
 * {@code null}.
 * @exception IOException if an error occurs during writing or when not
 * able to create required ImageOutputStream.
 */
public static boolean write(RenderedImage im,
                            String formatName,
                            File output) throws IOException {
    if (output == null) {
        throw new IllegalArgumentException("output == 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;
    }

    output.delete();
    ImageOutputStream stream = createImageOutputStream(output);
    if (stream == null) {
        throw new IIOException("Can't create an ImageOutputStream!");
    }
    try {
        return doWrite(im, writer, stream);
    } finally {
        stream.close();
    }
}
 
Example 27
Project: openjdk-jdk10   File: TIFFImageReader.java   Source Code and License 5 votes vote down vote up
public RenderedImage readAsRenderedImage(int imageIndex,
        ImageReadParam param)
        throws IOException {
    prepareRead(imageIndex, param);
    return new TIFFRenderedImage(this, imageIndex, imageReadParam,
            width, height);
}
 
Example 28
Project: Cognizant-Intelligent-Test-Scripter   File: ImageSpy.java   Source Code and License 5 votes vote down vote up
private void saveImage(String path, Image img) {
    try {
        new File(path).getParentFile().mkdirs();
        ImageIO.write((RenderedImage) img, "PNG", new File(path));
    } catch (IOException ex) {
        Logger.getLogger(ImageSpy.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 29
Project: jdk8u-jdk   File: GIFImageWriter.java   Source Code and License 5 votes vote down vote up
private boolean needToCreateIndex(RenderedImage image) {

        SampleModel sampleModel = image.getSampleModel();
        ColorModel colorModel = image.getColorModel();

        return sampleModel.getNumBands() != 1 ||
            sampleModel.getSampleSize()[0] > 8 ||
            colorModel.getComponentSize()[0] > 8;
    }
 
Example 30
Project: jdk8u-jdk   File: GIFImageWriter.java   Source Code and License 5 votes vote down vote up
private void writeRows(RenderedImage image, LZWCompressor compressor,
                       int sx, int sdx, int sy, int sdy, int sw,
                       int dy, int ddy, int dw, int dh,
                       int numRowsWritten, int progressReportRowPeriod)
  throws IOException {
    if (DEBUG) System.out.println("Writing unoptimized");

    int[] sbuf = new int[sw];
    byte[] dbuf = new byte[dw];

    Raster raster =
        image.getNumXTiles() == 1 && image.getNumYTiles() == 1 ?
        image.getTile(0, 0) : image.getData();
    for (int y = dy; y < dh; y += ddy) {
        if (numRowsWritten % progressReportRowPeriod == 0) {
            if (abortRequested()) {
                processWriteAborted();
                return;
            }
            processImageProgress((numRowsWritten*100.0F)/dh);
        }

        raster.getSamples(sx, sy, sw, 1, 0, sbuf);
        for (int i = 0, j = 0; i < dw; i++, j += sdx) {
            dbuf[i] = (byte)sbuf[j];
        }
        compressor.compress(dbuf, 0, dw);
        numRowsWritten++;
        sy += sdy;
    }
}
 
Example 31
Project: ostracker   File: FileUtil.java   Source Code and License 5 votes vote down vote up
public static void writeImage(RenderedImage image, String fileFormat, File file) {
    int timesAttempted = 0;

    do {
        try {
            ImageIO.write(image, fileFormat, file);
            break;
        } catch (Exception e) {
            e.printStackTrace();
        }
    } while (timesAttempted++ < TIMES_TO_ATTEMPT_WRITING_IMAGE);
}
 
Example 32
Project: jdk8u-jdk   File: ImageIO.java   Source Code and License 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example 33
Project: jdk8u-jdk   File: ImageIO.java   Source Code and License 5 votes vote down vote up
/**
 * Returns <code>ImageWriter</code> instance according to given
 * rendered image and image format or <code>null</code> if there
 * is no appropriate writer.
 */
private static ImageWriter getWriter(RenderedImage im,
                                     String formatName) {
    ImageTypeSpecifier type =
        ImageTypeSpecifier.createFromRenderedImage(im);
    Iterator<ImageWriter> iter = getImageWriters(type, formatName);

    if (iter.hasNext()) {
        return iter.next();
    } else {
        return null;
    }
}
 
Example 34
Project: Helpers   File: GifWriter.java   Source Code and License 4 votes vote down vote up
public void add(RenderedImage image) throws IOException {
    writer.writeToSequence(new IIOImage(image, null, imageMetaData), imageWriteParam);
}
 
Example 35
Project: openjdk-jdk10   File: TIFFRenderedImage.java   Source Code and License 4 votes vote down vote up
public Vector<RenderedImage> getSources() {
    return null;
}
 
Example 36
Project: Helpers   File: ImageReader.java   Source Code and License 4 votes vote down vote up
private static RenderedImage readFile(String path) throws IOException {
    return ImageIO.read(Paths.get(path).toFile());
}
 
Example 37
Project: Helpers   File: ImageReader.java   Source Code and License 4 votes vote down vote up
public static RenderedImage read(String from) throws IOException {
    if (isWebsite(from))
        return readWebsite(from);
    return readFile(from);
}
 
Example 38
Project: openjdk-jdk10   File: PaletteBuilder.java   Source Code and License 4 votes vote down vote up
protected PaletteBuilder(RenderedImage src) {
    this(src, 256);
}
 
Example 39
Project: openjdk-jdk10   File: ImageIO.java   Source Code and License 4 votes vote down vote up
/**
 * Writes an image using the an arbitrary {@code ImageWriter}
 * that supports the given format to an
 * {@code ImageOutputStream}.  The image is written to the
 * {@code ImageOutputStream} starting at the current stream
 * pointer, overwriting existing stream data from that point
 * forward, if present.
 *
 * <p> This method <em>does not</em> close the provided
 * {@code ImageOutputStream} after the write operation has completed;
 * it is the responsibility of the caller to close the stream, if desired.
 *
 * @param im a {@code RenderedImage} to be written.
 * @param formatName a {@code String} containing the informal
 * name of the format.
 * @param output an {@code ImageOutputStream} to be written to.
 *
 * @return {@code false} if no appropriate writer is found.
 *
 * @exception IllegalArgumentException if any parameter is
 * {@code null}.
 * @exception IOException if an error occurs during writing.
 */
public static boolean write(RenderedImage im,
                            String formatName,
                            ImageOutputStream output) throws IOException {
    if (im == null) {
        throw new IllegalArgumentException("im == null!");
    }
    if (formatName == null) {
        throw new IllegalArgumentException("formatName == null!");
    }
    if (output == null) {
        throw new IllegalArgumentException("output == null!");
    }

    return doWrite(im, getWriter(im, formatName), output);
}
 
Example 40
Project: OpenJSharp   File: RenderableImageOp.java   Source Code and License 4 votes vote down vote up
/**
 * Creates a RenderedImage which represents this
 * RenderableImageOp (including its Renderable sources) rendered
 * according to the given RenderContext.
 *
 * <p> This method supports chaining of either Renderable or
 * RenderedImage operations.  If sources in
 * the ParameterBlock used to construct the RenderableImageOp are
 * RenderableImages, then a three step process is followed:
 *
 * <ol>
 * <li> mapRenderContext() is called on the associated CRIF for
 * each RenderableImage source;
 * <li> createRendering() is called on each of the RenderableImage sources
 * using the backwards-mapped RenderContexts obtained in step 1,
 * resulting in a rendering of each source;
 * <li> ContextualRenderedImageFactory.create() is called
 * with a new ParameterBlock containing the parameters of
 * the RenderableImageOp and the RenderedImages that were created by the
 * createRendering() calls.
 * </ol>
 *
 * <p> If the elements of the source Vector of
 * the ParameterBlock used to construct the RenderableImageOp are
 * instances of RenderedImage, then the CRIF.create() method is
 * called immediately using the original ParameterBlock.
 * This provides a basis case for the recursion.
 *
 * <p> The created RenderedImage may have a property identified
 * by the String HINTS_OBSERVED to indicate which RenderingHints
 * (from the RenderContext) were used to create the image.
 * In addition any RenderedImages
 * that are obtained via the getSources() method on the created
 * RenderedImage may have such a property.
 *
 * @param renderContext The RenderContext to use to perform the rendering.
 * @return a RenderedImage containing the desired output image.
 */
public RenderedImage createRendering(RenderContext renderContext) {
    RenderedImage image = null;
    RenderContext rcOut = null;

    // Clone the original ParameterBlock; if the ParameterBlock
    // contains RenderableImage sources, they will be replaced by
    // RenderedImages.
    ParameterBlock renderedParamBlock = (ParameterBlock)paramBlock.clone();
    Vector sources = getRenderableSources();

    try {
        // This assumes that if there is no renderable source, that there
        // is a rendered source in paramBlock

        if (sources != null) {
            Vector renderedSources = new Vector();
            for (int i = 0; i < sources.size(); i++) {
                rcOut = myCRIF.mapRenderContext(i, renderContext,
                                                paramBlock, this);
                RenderedImage rdrdImage =
                   ((RenderableImage)sources.elementAt(i)).createRendering(rcOut);
                if (rdrdImage == null) {
                    return null;
                }

                // Add this rendered image to the ParameterBlock's
                // list of RenderedImages.
                renderedSources.addElement(rdrdImage);
            }

            if (renderedSources.size() > 0) {
                renderedParamBlock.setSources(renderedSources);
            }
        }

        return myCRIF.create(renderContext, renderedParamBlock);
    } catch (ArrayIndexOutOfBoundsException e) {
        // This should never happen
        return null;
    }
}