java.awt.image.RenderedImage Java Examples

The following examples show how to use java.awt.image.RenderedImage. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FXGraphics2D.java    From ccu-historian with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Converts a rendered image to a {@code BufferedImage}.  This utility
 * method has come from a forum post by Jim Moore at:
 * <p>
 * <a href="http://www.jguru.com/faq/view.jsp?EID=114602">
 * http://www.jguru.com/faq/view.jsp?EID=114602</a>
 * 
 * @param img  the rendered image.
 * 
 * @return A buffered image. 
 */
private static BufferedImage convertRenderedImage(RenderedImage img) {
    if (img instanceof BufferedImage) {
        return (BufferedImage) img;
    }
    ColorModel cm = img.getColorModel();
    int width = img.getWidth();
    int height = img.getHeight();
    WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
    boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
    Hashtable properties = new Hashtable();
    String[] keys = img.getPropertyNames();
    if (keys != null) {
        for (int i = 0; i < keys.length; i++) {
            properties.put(keys[i], img.getProperty(keys[i]));
        }
    }
    BufferedImage result = new BufferedImage(cm, raster, 
            isAlphaPremultiplied, properties);
    img.copyData(raster);
    return result;
}
 
Example #2
Source File: PaletteBuilder.java    From JDKSourceCode1.8 with MIT 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 #3
Source File: LoginController.java    From spring-security with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/getVerifyCode")
public void getVerifyCode(HttpServletRequest request, HttpServletResponse response){
    Map<String, Object> map = VerifyCodeUtil.getVerifyCode();
    HttpSession session = request.getSession();
    session.setAttribute(VerifyCodeUtil.SESSION_KEY, map.get(VerifyCodeUtil.SESSION_KEY));
    // 禁止图像缓存。
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");
    // 将图像输出到Servlet输出流中。
    try {
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write((RenderedImage) map.get(VerifyCodeUtil.BUFFIMG_KEY), "jpeg", sos);
        sos.close();
        //设置验证码过期时间
        VerifyCodeUtil.removeAttrbute(session);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #4
Source File: ImageTypeSpecifier.java    From openjdk-8-source with GNU General Public License v2.0 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 #5
Source File: ExporterToImage.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
private ExporterJob createImageExportJob(final File outputFile) {
  ExporterJob result = new ExporterJob("Export project") {
    @Override
    protected IStatus run() {
      Chart chart = getUIFacade().getActiveChart();

      // Test if there is an active chart
      if (chart == null) {
        // If not, it means we are running CLI
        String chartToExport = getPreferences().get("chart", null);

        // Default is to print Gantt chart
        chart = "resource".equals(chartToExport) ? getResourceChart() : getGanttChart();
      }
      RenderedImage renderedImage = chart.getRenderedImage(createExportSettings());
      try {
        ImageIO.write(renderedImage, myFileTypeOption.proposeFileExtension(), outputFile);
      } catch (IOException e) {
        getUIFacade().showErrorDialog(e);
        return Status.CANCEL_STATUS;
      }
      return Status.OK_STATUS;
    }
  };
  return result;
}
 
Example #6
Source File: TestMapcalc.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public void testMapcalc2() throws Exception {

        double[][] elevationData = HMTestMaps.flowData;
        HashMap<String, Double> envelopeParams = HMTestMaps.getEnvelopeparams();
        CoordinateReferenceSystem crs = HMTestMaps.getCrs();
        GridCoverage2D elevationCoverage = CoverageUtilities.buildCoverage("flow", elevationData, envelopeParams, crs, true);

        List<GridCoverage2D> maps = Arrays.asList(elevationCoverage);

        OmsMapcalc mapcalc = new OmsMapcalc();
        mapcalc.inRasters = maps;
        mapcalc.pFunction = "images{flow=read; dest=write;} dest = (flow+flow)/2;";

        mapcalc.process();

        GridCoverage2D outMap = mapcalc.outRaster;
        RenderedImage renderedImage = outMap.getRenderedImage();
        printImage(renderedImage);
        checkMatrixEqual(renderedImage, HMTestMaps.flowData, 0.000000001);
    }
 
Example #7
Source File: PNGImageWriter.java    From jdk8u_jdk with GNU General Public License v2.0 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 #8
Source File: Page.java    From libreveris with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new Page object.
 *
 * @param score the containing score
 * @param index page initial index in the containing image file, counted
 *              from 1.
 */
public Page (Score score,
             int index,
             RenderedImage image)
        throws StepException
{
    super(score);
    this.index = index;

    if (score.isMultiPage()) {
        id = score.getRadix() + "#" + index;
    } else {
        id = score.getRadix();
    }

    filterContext = new LiveParam<>(score.getFilterParam());
    textContext = new LiveParam<>(score.getTextParam());

    sheet = new Sheet(this, image);
}
 
Example #9
Source File: TargetBuilder.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Build a de-warped image according to target grid.
 */
public void buildInfo ()
{
    buildTarget();

    JaiDewarper dewarper = new JaiDewarper();

    // Define the dewarp grid
    buildWarpGrid(dewarper);

    // Dewarp the initial image
    RenderedImage dewarpedImage = dewarper.dewarpImage(sheet.getPicture().getImage(null));

    // Add a view on dewarped image?
    if (OMR.gui != null) {
        sheet.getStub().getAssembly().addViewTab(
                "Dewarped",
                new ScrollView(new DewarpedView(dewarpedImage)),
                null);
    }

    // Store dewarped image on disk
    if (constants.storeDewarp.getValue()) {
        storeImage(dewarpedImage);
    }
}
 
Example #10
Source File: ImageTypeSpecifier.java    From jdk8u-dev-jdk with GNU General Public License v2.0 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 #11
Source File: ImageIO.java    From dragonwell8_jdk with GNU General Public License v2.0 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 #12
Source File: GIFImageWriter.java    From openjdk-jdk8u with GNU General Public License v2.0 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 #13
Source File: ImageIO.java    From openjdk-8 with GNU General Public License v2.0 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 #14
Source File: ImageFileLayerType.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Layer createLayer(LayerContext ctx, PropertySet configuration) {
    final File file = (File) configuration.getValue(PROPERTY_NAME_IMAGE_FILE);
    final AffineTransform transform = (AffineTransform) configuration.getValue(PROPERTY_NAME_WORLD_TRANSFORM);
    RenderedImage image = FileLoadDescriptor.create(file.getPath(), null, true, null);
    final Rectangle2D modelBounds = DefaultMultiLevelModel.getModelBounds(transform, image);
    final DefaultMultiLevelModel model = new DefaultMultiLevelModel(1, transform, modelBounds);
    final MultiLevelSource multiLevelSource = new DefaultMultiLevelSource(image, model);
    return new ImageLayer(this, multiLevelSource, configuration);
}
 
Example #15
Source File: ImageIO.java    From openjdk-8 with GNU General Public License v2.0 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 #16
Source File: FXGraphics2D.java    From ECG-Viewer with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Draws the renderable image.
 * 
 * @param img  the renderable image.
 * @param xform  the transform.
 */
@Override
public void drawRenderableImage(RenderableImage img, 
        AffineTransform xform) {
    RenderedImage ri = img.createDefaultRendering();
    drawRenderedImage(ri, xform);
}
 
Example #17
Source File: LeptUtilsTest.java    From lept4j with Apache License 2.0 5 votes vote down vote up
/**
 * Test of getImageByteBuffer method, of class LeptUtils.
 */
@Test
@Ignore
public void testGetImageByteBuffer() throws Exception {
    System.out.println("getImageByteBuffer");
    RenderedImage image = null;
    ByteBuffer expResult = null;
    ByteBuffer result = LeptUtils.getImageByteBuffer(image);
    assertEquals(expResult, result);
}
 
Example #18
Source File: QuicklookSlstrDescriptor.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Create the Render Operator to compute SLSTR quicklook.
 *
 * <p>Creates a <code>ParameterBlockJAI</code> from all
 * supplied arguments except <code>hints</code> and invokes
 * {@link JAI#create(String,ParameterBlock,RenderingHints)}.
 *
 * @see JAI
 * @see ParameterBlockJAI
 * @see RenderedOp
 *
 * @return The <code>RenderedOp</code> destination.
 * @throws IllegalArgumentException if sources is null.
 * @throws IllegalArgumentException if a source is null.
 */
public static RenderedOp create(PixelCorrection[]pixels_correction,
   RenderingHints hints, RenderedImage... sources)
{
   ParameterBlockJAI pb =
      new ParameterBlockJAI(OPERATION_NAME,
            RenderedRegistryMode.MODE_NAME);

   int numSources = sources.length;
   // Check on the source number
   if (numSources <= 0)
   {
      throw new IllegalArgumentException("No resources are present");
   }
   
   // Setting of all the sources
   for (int index = 0; index < numSources; index++)
   {
      RenderedImage source = sources[index];
      if (source == null)
      {
         throw new IllegalArgumentException("This resource is null");
      }
      pb.setSource(source, index);
      pb.setParameter(paramNames[0], pixels_correction);
   }
   return JAI.create(OPERATION_NAME, pb, hints);
}
 
Example #19
Source File: CCDescriptor.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
/** Invokes the operator with a given ParameterBlock */

  public RenderedImage create(ParameterBlock paramBlock, 
			      RenderingHints renderHints)
  {
    return new CCOpImage(paramBlock.getRenderedSource(0),
			 (Rectangle) paramBlock.getObjectParameter(0));
  }
 
Example #20
Source File: PaletteBuilder.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
protected PaletteBuilder(RenderedImage src, int size) {
    this.src = src;
    this.srcColorModel = src.getColorModel();
    this.srcRaster = src.getData();

    this.transparency =
        srcColorModel.getTransparency();

    this.requiredSize = size;
}
 
Example #21
Source File: TexturePaintSerializationWrapper.java    From pumpernickel with MIT License 5 votes vote down vote up
public TexturePaintSerializationWrapper(TexturePaint tp) {
	ImageSerializationWrapper image = new ImageSerializationWrapper(
			(RenderedImage) tp.getImage());
	map.put(KEY_IMAGE, image);

	Rectangle2DSerializationWrapper anchor = new Rectangle2DSerializationWrapper(
			tp.getAnchorRect());
	map.put(KEY_ANCHOR_RECT, anchor);
}
 
Example #22
Source File: LegendBuilder.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
public void addLayer(String title, Font font, RenderedImage image) {
	JPanel panel = new JPanel();
	panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
	RenderedImageIcon icon = new RenderedImageIcon(image,
			LegendGraphicMetadata.DEFAULT_WIDTH, LegendGraphicMetadata.DEFAULT_HEIGHT);
	JLabel label = new JLabel(icon);
	label.setBorder(new EmptyBorder(ICON_PADDING, ICON_PADDING, ICON_PADDING, ICON_PADDING));
	panel.add(label);
	panel.add(Box.createRigidArea(new Dimension(MEMBER_MARGIN, 0)));
	JLabel itemText = new JLabel(title);
	itemText.setFont(font);
	panel.add(itemText);
	panel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
	legendPanel.add(panel);
}
 
Example #23
Source File: CustomIconLoader.java    From intellij-extra-icons-plugin with MIT License 5 votes vote down vote up
public static String toBase64(ImageWrapper imageWrapper) {
    String base64 = null;
    IconType iconType = imageWrapper.getIconType();
    switch (iconType) {
        case SVG:
            base64 = Base64.encode(imageWrapper.getImageAsByteArray());
            break;
        case IMG:
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            try {
                Image image = imageWrapper.getImage();
                if (image instanceof JBHiDPIScaledImage) {
                    image = ((JBHiDPIScaledImage) image).getDelegate();
                }
                if (image instanceof ToolkitImage) {
                    image = ((ToolkitImage) image).getBufferedImage();
                }
                if (!(image instanceof RenderedImage)) {
                    BufferedImage bufferedImage = UIUtil.createImage(
                        GRAPHICS_CFG,
                        image.getWidth(null),
                        image.getHeight(null),
                        BufferedImage.TYPE_INT_RGB,
                        PaintUtil.RoundingMode.ROUND);
                    bufferedImage.getGraphics().drawImage(image, 0, 0, null);
                    image = bufferedImage;
                }
                ImageIO.write((RenderedImage) image, "png", outputStream);
            } catch (IOException ex) {
                LOGGER.info("Can't load " + iconType + " icon: " + ex.getMessage(), ex);
            }
            base64 = Base64.encode(outputStream.toByteArray());
            break;
    }
    return base64;
}
 
Example #24
Source File: TIFFImageWriter.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
public void prepareWriteEmpty(IIOMetadata streamMetadata,
                              ImageTypeSpecifier imageType,
                              int width,
                              int height,
                              IIOMetadata imageMetadata,
                              List<? extends BufferedImage> thumbnails,
                              ImageWriteParam param) throws IOException {
    if (stream == null) {
        throw new IllegalStateException("output == null!");
    }

    checkParamsEmpty(imageType, width, height, thumbnails);

    this.isWritingEmpty = true;

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

    markPositions();
    write(streamMetadata, new IIOImage(emptyImage, null, imageMetadata),
          param, true, false);
    if (abortRequested()) {
        resetPositions();
    }
}
 
Example #25
Source File: GIFImageWriter.java    From jdk8u-jdk with GNU General Public License v2.0 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 #26
Source File: ImageIO.java    From jdk8u60 with GNU General Public License v2.0 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 #27
Source File: ImageIO.java    From jdk1.8-source-analysis with Apache License 2.0 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 #28
Source File: MaskFormActions.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private Rectangle2D handleImageMask(Mask mask, AffineTransform i2m) {
    RenderedImage image = mask.getSourceImage().getImage(0);
    final int minTileX = image.getMinTileX();
    final int minTileY = image.getMinTileY();
    final int numXTiles = image.getNumXTiles();
    final int numYTiles = image.getNumYTiles();
    final int width = image.getWidth();
    final int height = image.getHeight();
    int minX = width;
    int maxX = 0;
    int minY = height;
    int maxY = 0;

    for (int tileX = minTileX; tileX < minTileX + numXTiles; ++tileX) {
        for (int tileY = minTileY; tileY < minTileY + numYTiles; ++tileY) {
            final Raster data = image.getTile(tileX, tileY);
            for (int x = data.getMinX(); x < data.getMinX() + data.getWidth(); x++) {
                for (int y = data.getMinY(); y < data.getMinY() + data.getHeight(); y++) {
                    if (data.getSample(x, y, 0) != 0) {
                        minX = Math.min(x, minX);
                        maxX = Math.max(x, maxX);
                        minY = Math.min(y, minY);
                        maxY = Math.max(y, maxY);
                    }
                }
            }
        }
    }
    Rectangle rect = new Rectangle(minX, minY, maxX - minX + 1, maxY - minY + 1);
    if (rect.isEmpty()) {
        return null;
    } else {
        return i2m.createTransformedShape(rect).getBounds2D();
    }
}
 
Example #29
Source File: ImageIO.java    From openjdk-jdk9 with GNU General Public License v2.0 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 #30
Source File: CCOpImage.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
/** Constructs a CCOpImage object */

  public CCOpImage(RenderedImage source, Rectangle sample) {
    super(source, new ROIShape(new Rectangle(source.getMinX(), source.getMinY(), 
					     source.getWidth(), source.getHeight())),
	  source.getMinX(), source.getMinY(),
	  1, 1);

    sampleRectangle = sample;
    image = source;
  }