Example usage for java.awt Graphics2D drawImage

List of usage examples for java.awt Graphics2D drawImage

Introduction

In this page you can find the example usage for java.awt Graphics2D drawImage.

Prototype

public abstract void drawImage(BufferedImage img, BufferedImageOp op, int x, int y);

Source Link

Document

Renders a BufferedImage that is filtered with a BufferedImageOp .

Usage

From source file:com.igormaznitsa.jhexed.swing.editor.ui.exporters.PNGImageExporter.java

public BufferedImage generateImage() throws IOException {
    final int DEFAULT_CELL_WIDTH = 48;
    final int DEFAULT_CELL_HEIGHT = 48;

    final int imgWidth = this.docOptions.getImage() == null ? DEFAULT_CELL_WIDTH * this.docOptions.getColumns()
            : Math.round(this.docOptions.getImage().getSVGWidth());
    final int imgHeight = this.docOptions.getImage() == null ? DEFAULT_CELL_HEIGHT * this.docOptions.getRows()
            : Math.round(this.docOptions.getImage().getSVGHeight());

    final BufferedImage result;
    if (exportData.isBackgroundImageExport() && this.docOptions.getImage() != null) {
        result = this.docOptions.getImage().rasterize(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
    } else {//from  w w w.j a  v  a2 s.co m
        result = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
    }

    final Graphics2D gfx = result.createGraphics();
    gfx.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    gfx.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    final HexEngine<Graphics2D> engine = new HexEngine<Graphics2D>(DEFAULT_CELL_WIDTH, DEFAULT_CELL_HEIGHT,
            this.docOptions.getHexOrientation());

    final List<HexFieldLayer> reversedNormalizedStack = new ArrayList<HexFieldLayer>();
    for (int i = this.exportData.getLayers().size() - 1; i >= 0; i--) {
        final LayerExportRecord rec = this.exportData.getLayers().get(i);
        if (rec.isAllowed()) {
            reversedNormalizedStack.add(rec.getLayer());
        }
    }

    if (Thread.currentThread().isInterrupted())
        return null;

    final HexFieldValue[] stackOfValues = new HexFieldValue[reversedNormalizedStack.size()];

    engine.setModel(new HexEngineModel<HexFieldValue[]>() {

        @Override
        public int getColumnNumber() {
            return docOptions.getColumns();
        }

        @Override
        public int getRowNumber() {
            return docOptions.getRows();
        }

        @Override
        public HexFieldValue[] getValueAt(final int col, final int row) {
            Arrays.fill(stackOfValues, null);

            for (int index = 0; index < reversedNormalizedStack.size(); index++) {
                stackOfValues[index] = reversedNormalizedStack.get(index).getHexValueAtPos(col, row);
            }
            return stackOfValues;
        }

        @Override
        public HexFieldValue[] getValueAt(final HexPosition pos) {
            return this.getValueAt(pos.getColumn(), pos.getRow());
        }

        @Override
        public void setValueAt(int col, int row, HexFieldValue[] value) {
        }

        @Override
        public void setValueAt(HexPosition pos, HexFieldValue[] value) {
        }

        @Override
        public boolean isPositionValid(final int col, final int row) {
            return col >= 0 && col < docOptions.getColumns() && row >= 0 && row < docOptions.getRows();
        }

        @Override
        public boolean isPositionValid(final HexPosition pos) {
            return this.isPositionValid(pos.getColumn(), pos.getRow());
        }

        @Override
        public void attachedToEngine(final HexEngine<?> engine) {
        }

        @Override
        public void detachedFromEngine(final HexEngine<?> engine) {
        }
    });

    final HexRect2D visibleSize = engine.getVisibleSize();
    final float xcoeff = (float) result.getWidth() / visibleSize.getWidth();
    final float ycoeff = (float) result.getHeight() / visibleSize.getHeight();
    engine.setScale(xcoeff, ycoeff);

    final Image[][] cachedIcons = new Image[this.exportData.getLayers().size()][];
    engine.setRenderer(new ColorHexRender() {

        private final Stroke stroke = new BasicStroke(docOptions.getLineWidth());

        @Override
        public Stroke getStroke() {
            return this.stroke;
        }

        @Override
        public Color getFillColor(HexEngineModel<?> model, int col, int row) {
            return null;
        }

        @Override
        public Color getBorderColor(HexEngineModel<?> model, int col, int row) {
            return exportData.isExportHexBorders() ? docOptions.getColor() : null;
        }

        @Override
        public void drawExtra(HexEngine<Graphics2D> engine, Graphics2D g, int col, int row, Color borderColor,
                Color fillColor) {
        }

        @Override
        public void drawUnderBorder(final HexEngine<Graphics2D> engine, final Graphics2D g, final int col,
                final int row, final Color borderColor, final Color fillColor) {
            final HexFieldValue[] stackValues = (HexFieldValue[]) engine.getModel().getValueAt(col, row);
            for (int i = 0; i < stackValues.length; i++) {
                final HexFieldValue valueToDraw = stackValues[i];
                if (valueToDraw == null) {
                    continue;
                }
                g.drawImage(cachedIcons[i][valueToDraw.getIndex()], 0, 0, null);
            }
        }

    });

    final Path2D hexShape = ((ColorHexRender) engine.getRenderer()).getHexPath();
    final int cellWidth = hexShape.getBounds().width;
    final int cellHeight = hexShape.getBounds().height;

    for (int layerIndex = 0; layerIndex < reversedNormalizedStack.size()
            && !Thread.currentThread().isInterrupted(); layerIndex++) {
        final HexFieldLayer theLayer = reversedNormalizedStack.get(layerIndex);
        final Image[] cacheLineForLayer = new Image[theLayer.getHexValuesNumber()];
        for (int valueIndex = 1; valueIndex < theLayer.getHexValuesNumber(); valueIndex++) {
            cacheLineForLayer[valueIndex] = theLayer.getHexValueForIndex(valueIndex).makeIcon(cellWidth,
                    cellHeight, hexShape, true);
        }
        cachedIcons[layerIndex] = cacheLineForLayer;
    }

    engine.drawWithThreadInterruptionCheck(gfx);
    if (Thread.currentThread().isInterrupted())
        return null;

    if (this.exportData.isCellCommentariesExport()) {
        final Iterator<Entry<HexPosition, String>> iterator = this.cellComments.iterator();
        gfx.setFont(new Font("Arial", Font.BOLD, 12));
        while (iterator.hasNext() && !Thread.currentThread().isInterrupted()) {
            final Entry<HexPosition, String> item = iterator.next();
            final HexPosition pos = item.getKey();
            final String text = item.getValue();
            final float x = engine.calculateX(pos.getColumn(), pos.getRow());
            final float y = engine.calculateY(pos.getColumn(), pos.getRow());

            final Rectangle2D textBounds = gfx.getFontMetrics().getStringBounds(text, gfx);

            final float dx = x - ((float) textBounds.getWidth() - engine.getCellWidth()) / 2;

            gfx.setColor(Color.BLACK);
            gfx.drawString(text, dx, y);
            gfx.setColor(Color.WHITE);
            gfx.drawString(text, dx - 2, y - 2);
        }
    }

    gfx.dispose();

    return result;
}

From source file:TrackerPanel.java

private void drawUserDepths(Graphics2D g2d) {
    // define an 8-bit RGB channel color model
    ColorModel colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
            new int[] { 8, 8, 8 }, false, false, ComponentColorModel.OPAQUE, DataBuffer.TYPE_BYTE);

    // fill the raster with the depth image bytes
    DataBufferByte dataBuffer = new DataBufferByte(imgbytes, imWidth * imHeight * 3);

    WritableRaster raster = Raster.createInterleavedRaster(dataBuffer, imWidth, imHeight, imWidth * 3, 3,
            new int[] { 0, 1, 2 }, null);

    // combine color model and raster to create a BufferedImage
    BufferedImage image = new BufferedImage(colorModel, raster, false, null);

    g2d.drawImage(image, 0, 0, null);
}

From source file:gdt.jgui.entity.webset.JWeblinkEditor.java

private void showIconMenu(MouseEvent e) {
    try {/*from w  w  w .jav a 2 s  . com*/
        iconMenu = new JPopupMenu();
        JMenuItem loadItem = new JMenuItem("Load");
        iconMenu.add(loadItem);
        loadItem.setHorizontalTextPosition(JMenuItem.RIGHT);
        loadItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    String favicon$ = "http://www.google.com/s2/favicons?domain=" + addressField.getText();
                    URL url = new URL(favicon$);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    ImageIcon icon = new ImageIcon(ImageIO.read(input));
                    int type = BufferedImage.TYPE_INT_RGB;
                    BufferedImage out = new BufferedImage(24, 24, type);
                    Color background = JWeblinkEditor.this.getBackground();
                    Graphics2D g2 = out.createGraphics();
                    g2.setBackground(background);
                    g2.clearRect(0, 0, 24, 24);
                    Image image = icon.getImage();
                    g2.drawImage(image, 4, 4, null);
                    g2.dispose();
                    icon = new ImageIcon(out);
                    iconIcon.setIcon(icon);
                    input.close();
                } catch (Exception ee) {
                    Logger.getLogger(getClass().getName()).info(ee.toString());
                }
            }
        });
        JMenuItem setItem = new JMenuItem("Set");
        iconMenu.add(setItem);
        setItem.setHorizontalTextPosition(JMenuItem.RIGHT);
        setItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("WeblinkEditor:set icon");
                JIconSelector is = new JIconSelector();
                String isLocator$ = is.getLocator();
                if (entihome$ != null)
                    isLocator$ = Locator.append(isLocator$, Entigrator.ENTIHOME, entihome$);
                if (entityKey$ != null)
                    isLocator$ = Locator.append(isLocator$, EntityHandler.ENTITY_KEY, entityKey$);

                String responseLocator$ = getLocator();
                responseLocator$ = Locator.append(responseLocator$, JRequester.REQUESTER_ACTION,
                        ACTION_SET_ICON);
                responseLocator$ = Locator.append(responseLocator$, BaseHandler.HANDLER_METHOD, "response");
                isLocator$ = Locator.append(isLocator$, JRequester.REQUESTER_RESPONSE_LOCATOR,
                        Locator.compressText(responseLocator$));
                JConsoleHandler.execute(console, isLocator$);
            }
        });
        iconMenu.show(e.getComponent(), e.getX(), e.getY());
    } catch (Exception ee) {
        Logger.getLogger(getClass().getName()).severe(ee.toString());
    }
}

From source file:org.fhcrc.cpl.viewer.quant.gui.PanelWithSpectrumChart.java

License:asdf

/**
 *
 * @param imageWidthEachScan//w ww . j a  v a  2 s  . co  m
 * @param imageHeightEachScan
 * @param maxTotalImageHeight a hard boundary on the total image height.  If imageHeightEachScan is too big,
 * given the total number of charts and this arg, it gets knocked down
 * @param outputFile
 * @throws java.io.IOException
 */
public void savePerScanSpectraImage(int imageWidthEachScan, int imageHeightEachScan, int maxTotalImageHeight,
        File outputFile) throws IOException {
    int numCharts = scanLineChartMap.size();

    int widthPaddingForLabels = 50;

    imageHeightEachScan = Math.min(imageHeightEachScan, maxTotalImageHeight / numCharts);

    List<Integer> allScanNumbers = new ArrayList<Integer>(scanLineChartMap.keySet());
    Collections.sort(allScanNumbers);
    List<PanelWithChart> allCharts = new ArrayList<PanelWithChart>();

    for (int scanNumber : allScanNumbers) {
        PanelWithLineChart scanChart = scanLineChartMap.get(scanNumber);
        allCharts.add(scanChart);
        scanChart.setSize(imageWidthEachScan - widthPaddingForLabels, imageHeightEachScan);
    }

    BufferedImage perScanChartImage = MultiChartDisplayPanel.createImageForAllCharts(allCharts);

    BufferedImage perScanChartImageWithLabels = new BufferedImage(imageWidthEachScan,
            perScanChartImage.getHeight(), BufferedImage.TYPE_INT_RGB);

    Graphics2D g = perScanChartImageWithLabels.createGraphics();
    g.drawImage(perScanChartImage, widthPaddingForLabels, 0, null);
    g.setPaint(Color.WHITE);
    g.drawRect(0, 0, widthPaddingForLabels, perScanChartImage.getHeight());

    for (int i = 0; i < allCharts.size(); i++) {
        int scanNumber = allScanNumbers.get(i);

        int chartTop = i * imageHeightEachScan;
        int chartMiddle = chartTop + (imageHeightEachScan / 2);

        if (lightFirstScanLine > 0 && lightLastScanLine > 0) {
            if (scanNumber >= lightFirstScanLine && scanNumber <= lightLastScanLine)
                g.setPaint(Color.GREEN);
            else
                g.setPaint(Color.RED);
        } else
            g.setPaint(Color.BLACK);

        g.drawString("" + scanNumber, 5, chartMiddle);
    }
    g.dispose();

    ImageIO.write(perScanChartImageWithLabels, "png", outputFile);
}

From source file:com.nbt.TileCanvas.java

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g.create();

    g2d.setColor(Color.BLACK);//from w ww . ja v a2s. co m
    int x = 0, y = 0;
    Dimension size = getSize();
    g2d.fillRect(x, y, size.width, size.height);

    final int altitude = getAltitude();
    for (int w = 0; w < getTileWidth(); w++) {
        x = w * SPRITE_SIZE;
        for (int h = 0; h < getTileHeight(); h++) {
            y = h * SPRITE_SIZE;

            int xOffset = w + getTileX();
            int zOffset = h + getTileZ();
            BufferedImage tile = getBackgroundTile(xOffset, altitude, zOffset);
            if (tile != null)
                g2d.drawImage(tile, x, y, null);
        }
    }

    g2d.dispose();
}

From source file:de._13ducks.cor.graphics.GraphicsComponent.java

private void renderCursor(Graphics2D g2) {
    if (!renderPicCursor) {
        boolean[][] curArray = drawCursor.getFieldShadow();
        for (int x = 0; x < curArray.length; x++) {
            for (int y = 0; y < curArray[0].length; y++) {
                if ((x + y) % 2 == 1) {
                    continue;
                }//  w w  w. ja v a 2 s .  c  o  m
                if (curArray[x][y]) {
                    g2.drawImage(imgMap.get("cur1").getImage(), (framePos.width + x) * 10,
                            (int) ((framePos.height + y) * 7.5), null);
                }
            }
        }

    } else {
        // Pic-Cursor
        // Einfach Bild an die gerasterte Cursorposition rendern.
        g2.drawImage(renderPic.getImage(), framePos.width * 10, (int) (framePos.height * 7.5), null);
    }
}

From source file:net.pms.util.GenericIcons.java

/**
 * Add the format(container) name of the media to the generic icon image.
 *
 * @param image BufferdImage to be the label added
 * @param label the media container name to be added as a label
 * @param renderer the renderer configuration
 *
 * @return the generic icon with the container label added and scaled in accordance with renderer setting
 *///from  ww  w .  j a va 2s .  c  om
private DLNAThumbnail addFormatLabelToImage(String label, ImageFormat imageFormat, IconType iconType)
        throws IOException {

    BufferedImage image;
    switch (iconType) {
    case AUDIO:
        image = genericAudioIcon;
        break;
    case IMAGE:
        image = genericImageIcon;
        break;
    case VIDEO:
        image = genericVideoIcon;
        break;
    default:
        image = genericUnknownIcon;
    }

    if (image != null) {
        // Make a copy
        ColorModel colorModel = image.getColorModel();
        image = new BufferedImage(colorModel, image.copyData(null), colorModel.isAlphaPremultiplied(), null);
    }

    ByteArrayOutputStream out = null;

    if (label != null && image != null) {
        out = new ByteArrayOutputStream();
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        try {
            int size = 40;
            Font font = new Font(Font.SANS_SERIF, Font.BOLD, size);
            FontMetrics metrics = g.getFontMetrics(font);
            while (size > 7 && metrics.stringWidth(label) > 135) {
                size--;
                font = new Font(Font.SANS_SERIF, Font.BOLD, size);
                metrics = g.getFontMetrics(font);
            }
            // Text center point 127x, 49y - calculate centering coordinates
            int x = 127 - metrics.stringWidth(label) / 2;
            int y = 46 + metrics.getAscent() / 2;
            g.drawImage(image, 0, 0, null);
            g.setColor(Color.WHITE);
            g.setFont(font);
            g.drawString(label, x, y);

            ImageIO.setUseCache(false);
            ImageIOTools.imageIOWrite(image, imageFormat.toString(), out);
        } finally {
            g.dispose();
        }
    }
    return out != null ? DLNAThumbnail.toThumbnail(out.toByteArray(), 0, 0, ScaleType.MAX, imageFormat, false)
            : null;
}

From source file:main.MapKit.java

@Override
public void paintWaypoint(Graphics2D g, JXMapViewer viewer, MyWaypoint w) {
    g = (Graphics2D) g.create();//w w w  .  ja  v  a2  s .  c o  m

    Point2D point = viewer.getTileFactory().geoToPixel(w.getPosition(), viewer.getZoom());
    int x = (int) point.getX();
    int y = (int) point.getY();

    if (w.amount == -1) { //means it's an original data point
        int fontSize = 28 - viewer.getZoom() * 2; //font size is larger when zoom in
        if (fontSize < 6)
            fontSize = 6;
        g.setFont(new Font("Arial", Font.PLAIN, fontSize));
        g.setColor(w.color);
        g.drawString("x", x - fontSize / 2, y + fontSize / 2);
        g.dispose();
        return;
    }

    if (origImage == null) {
        return;
    }

    BufferedImage myImg = map.get(w.color);

    if (myImg == null) {
        myImg = convert(origImage, w.color);
        map.put(w.color, myImg);
    }

    g.drawImage(myImg, x - myImg.getWidth() / 2, y - myImg.getHeight(), null);

    String label = String.valueOf(w.amount);

    //      g.setFont(font);
    FontMetrics metrics = g.getFontMetrics();
    int tw = metrics.stringWidth(label);
    int th = 1 + metrics.getAscent();

    //      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.drawString(label, x - tw / 2, y + th);

    g.dispose();
}

From source file:org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap.java

/**
 * Returns a {@link java.awt.image.BufferedImage} of the COSStream
 * set in the constructor or null if the COSStream could not be encoded.
 *
 * @return {@inheritDoc}/*from   ww  w  .  j av  a2  s. c o m*/
 *
 * @throws IOException {@inheritDoc}
 */
public BufferedImage getRGBImage() throws IOException {
    if (image != null) {
        return image;
    }

    try {
        int width = getWidth();
        int height = getHeight();
        int bpc = getBitsPerComponent();

        byte[] array = getPDStream().getByteArray();
        if (array.length == 0) {
            LOG.error("Something went wrong ... the pixelmap doesn't contain any data.");
            return null;
        }
        // Get the ColorModel right
        PDColorSpace colorspace = getColorSpace();
        if (colorspace == null) {
            LOG.error("getColorSpace() returned NULL.  Predictor = " + getPredictor());
            return null;
        }

        ColorModel cm = null;
        if (colorspace instanceof PDIndexed) {
            PDIndexed csIndexed = (PDIndexed) colorspace;
            // the base color space uses 8 bit per component, as the indexed color values
            // of an indexed color space are always in a range from 0 to 255
            ColorModel baseColorModel = csIndexed.getBaseColorSpace().createColorModel(8);
            // number of possible color values in the target color space
            int numberOfColorValues = 1 << bpc;
            // number of indexed color values
            int highValue = csIndexed.getHighValue();
            // choose the correct size, sometimes there are more indexed values than needed
            // and sometimes there are fewer indexed value than possible
            int size = Math.min(numberOfColorValues - 1, highValue);
            byte[] index = csIndexed.getLookupData();
            boolean hasAlpha = baseColorModel.hasAlpha();
            COSBase maskArray = getMask();
            if (baseColorModel.getTransferType() != DataBuffer.TYPE_BYTE) {
                throw new IOException("Not implemented");
            }
            // the IndexColorModel uses RGB-based color values
            // which leads to 3 color components and a optional alpha channel
            int numberOfComponents = 3 + (hasAlpha ? 1 : 0);
            int buffersize = (size + 1) * numberOfComponents;
            byte[] colorValues = new byte[buffersize];
            byte[] inData = new byte[baseColorModel.getNumComponents()];
            int bufferIndex = 0;
            for (int i = 0; i <= size; i++) {
                System.arraycopy(index, i * inData.length, inData, 0, inData.length);
                // convert the indexed color values to RGB 
                colorValues[bufferIndex] = (byte) baseColorModel.getRed(inData);
                colorValues[bufferIndex + 1] = (byte) baseColorModel.getGreen(inData);
                colorValues[bufferIndex + 2] = (byte) baseColorModel.getBlue(inData);
                if (hasAlpha) {
                    colorValues[bufferIndex + 3] = (byte) baseColorModel.getAlpha(inData);
                }
                bufferIndex += numberOfComponents;
            }
            if (maskArray != null && maskArray instanceof COSArray) {
                cm = new IndexColorModel(bpc, size + 1, colorValues, 0, hasAlpha,
                        ((COSArray) maskArray).getInt(0));
            } else {
                cm = new IndexColorModel(bpc, size + 1, colorValues, 0, hasAlpha);
            }
        } else if (colorspace instanceof PDSeparation) {
            PDSeparation csSeparation = (PDSeparation) colorspace;
            int numberOfComponents = csSeparation.getAlternateColorSpace().getNumberOfComponents();
            PDFunction tintTransformFunc = csSeparation.getTintTransform();
            COSArray decode = getDecode();
            // we have to invert the tint-values,
            // if the Decode array exists and consists of (1,0)
            boolean invert = decode != null && decode.getInt(0) == 1;
            // TODO add interpolation for other decode values then 1,0
            int maxValue = (int) Math.pow(2, bpc) - 1;
            // destination array
            byte[] mappedData = new byte[width * height * numberOfComponents];
            int rowLength = width * numberOfComponents;
            float[] input = new float[1];
            for (int i = 0; i < height; i++) {
                int rowOffset = i * rowLength;
                for (int j = 0; j < width; j++) {
                    // scale tint values to a range of 0...1
                    int value = (array[i * width + j] + 256) % 256;
                    if (invert) {
                        input[0] = 1 - (value / maxValue);
                    } else {
                        input[0] = value / maxValue;
                    }
                    float[] mappedColor = tintTransformFunc.eval(input);
                    int columnOffset = j * numberOfComponents;
                    for (int k = 0; k < numberOfComponents; k++) {
                        // redo scaling for every single color value 
                        float mappedValue = mappedColor[k];
                        mappedData[rowOffset + columnOffset + k] = (byte) (mappedValue * maxValue);
                    }
                }
            }
            array = mappedData;
            cm = colorspace.createColorModel(bpc);
        } else if (bpc == 1) {
            byte[] map = null;
            if (colorspace instanceof PDDeviceGray) {
                COSArray decode = getDecode();
                // we have to invert the b/w-values,
                // if the Decode array exists and consists of (1,0)
                if (decode != null && decode.getInt(0) == 1) {
                    map = new byte[] { (byte) 0xff };
                } else {
                    map = new byte[] { (byte) 0x00, (byte) 0xff };
                }
            } else if (colorspace instanceof PDICCBased) {
                if (((PDICCBased) colorspace).getNumberOfComponents() == 1) {
                    map = new byte[] { (byte) 0xff };
                } else {
                    map = new byte[] { (byte) 0x00, (byte) 0xff };
                }
            } else {
                map = new byte[] { (byte) 0x00, (byte) 0xff };
            }
            cm = new IndexColorModel(bpc, map.length, map, map, map, Transparency.OPAQUE);
        } else {
            if (colorspace instanceof PDICCBased) {
                if (((PDICCBased) colorspace).getNumberOfComponents() == 1) {
                    byte[] map = new byte[] { (byte) 0xff };
                    cm = new IndexColorModel(bpc, 1, map, map, map, Transparency.OPAQUE);
                } else {
                    cm = colorspace.createColorModel(bpc);
                }
            } else {
                cm = colorspace.createColorModel(bpc);
            }
        }

        LOG.debug("ColorModel: " + cm.toString());
        WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
        DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
        byte[] bufferData = buffer.getData();

        System.arraycopy(array, 0, bufferData, 0,
                (array.length < bufferData.length ? array.length : bufferData.length));
        image = new BufferedImage(cm, raster, false, null);

        // If there is a 'soft mask' image then we use that as a transparency mask.
        PDXObjectImage smask = getSMaskImage();
        if (smask != null) {
            BufferedImage smaskBI = smask.getRGBImage();

            COSArray decodeArray = smask.getDecode();

            CompositeImage compositeImage = new CompositeImage(image, smaskBI);
            BufferedImage rgbImage = compositeImage.createMaskedImage(decodeArray);

            return rgbImage;
        } else if (getImageMask()) {
            BufferedImage stencilMask = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D graphics = (Graphics2D) stencilMask.getGraphics();
            if (getStencilColor() != null) {
                graphics.setColor(getStencilColor().getJavaColor());
            } else {
                // this might happen when using ExractImages, see PDFBOX-1145
                LOG.debug("no stencil color for PixelMap found, using Color.BLACK instead.");
                graphics.setColor(Color.BLACK);
            }

            graphics.fillRect(0, 0, width, height);
            // assume default values ([0,1]) for the DecodeArray
            // TODO DecodeArray == [1,0]
            graphics.setComposite(AlphaComposite.DstIn);
            graphics.drawImage(image, null, 0, 0);
            return stencilMask;
        } else {
            // if there is no mask, use the unaltered image.
            return image;
        }
    } catch (Exception exception) {
        LOG.error(exception, exception);
        //A NULL return is caught in pagedrawer.Invoke.process() so don't re-throw.
        //Returning the NULL falls through to Phillip Koch's TODO section.
        return null;
    }
}

From source file:de._13ducks.cor.graphics.GraphicsComponent.java

private void renderUnits(Graphics2D g2) {
    selectionShadows = new ArrayList();
    if (unitList != null) {
        for (int i = 0; i < unitList.size(); i++) {
            // Liste durchgehen
            Unit unit = unitList.get(i);
            // Einheit an aktuelle Position rendern
            String tex = unit.getGraphicsData().getTexture();
            CoRImage tempImage = imgMap.get(tex);
            if (tempImage != null) {
                // Einheit zeichnen
                g2.drawImage(tempImage.getImage(), (unit.getMainPosition().getX() - positionX) * 10,
                        (int) ((unit.getMainPosition().getY() - positionY) * 7.5), null);

            } else {
                System.out.println("[RogGraphics][ERROR]: Image \"" + tex + "\" not found!");
            }/*from ww w  .  j av a 2s.co m*/

        }
    }
}