Example usage for java.awt.image BufferedImage getGraphics

List of usage examples for java.awt.image BufferedImage getGraphics

Introduction

In this page you can find the example usage for java.awt.image BufferedImage getGraphics.

Prototype

public java.awt.Graphics getGraphics() 

Source Link

Document

This method returns a Graphics2D , but is here for backwards compatibility.

Usage

From source file:de.tor.tribes.ui.views.DSWorkbenchRankFrame.java

@Override
public void actionPerformed(ActionEvent e) {
    RankTableTab activeTab = getActiveTab();
    if (e.getActionCommand() != null && activeTab != null) {
        if (e.getActionCommand().equals("Find")) {
            BufferedImage back = ImageUtils.createCompatibleBufferedImage(3, 3, BufferedImage.TRANSLUCENT);
            Graphics g = back.getGraphics();
            g.setColor(new Color(120, 120, 120, 120));
            g.fillRect(0, 0, back.getWidth(), back.getHeight());
            g.setColor(new Color(120, 120, 120));
            g.drawLine(0, 0, 3, 3);/*  w  w w.ja v a  2 s.  c o m*/
            g.dispose();
            TexturePaint paint = new TexturePaint(back,
                    new Rectangle2D.Double(0, 0, back.getWidth(), back.getHeight()));
            jxSearchPane.setBackgroundPainter(new MattePainter(paint));
            DefaultListModel model = new DefaultListModel();

            for (int i = 0; i < activeTab.getRankTable().getColumnCount(); i++) {
                TableColumnExt col = activeTab.getRankTable().getColumnExt(i);
                if (col.isVisible()) {
                    if (col.getTitle().equals("Name") || col.getTitle().equals("Tag")
                            || col.getTitle().equals("Stamm")) {
                        model.addElement(col.getTitle());
                    }

                }
            }
            jXColumnList.setModel(model);
            jXColumnList.setSelectedIndex(0);
            jxSearchPane.setVisible(true);
        }
    }

}

From source file:org.eclipse.wb.internal.swing.utils.SwingScreenshotMaker.java

/**
 * Traverses through components hierarchy and prepares screen shot for every component needed.
 * /*from w ww .j  a va 2  s.c om*/
 * Note: it doesn't make top component not visible, use {@link #dispose()} for that.
 * 
 * Important note: must be called from AWT dispatch thread.
 */
public void makeShots() throws Exception {
    SwingImageUtils.checkForDialog(m_component);
    final int componentWidth = Math.max(1, m_component.getWidth());
    final int componentHeight = Math.max(1, m_component.getHeight());
    m_oldComponentLocation = m_component.getLocation();
    SwingImageUtils.prepareForPrinting(m_window);
    fixJLabelWithHTML(m_component);
    // prepare empty image
    BufferedImage image;
    // prepare window image
    final BufferedImage windowImage;
    // print component and its children
    {
        int windowWidth = Math.max(1, m_window.getWidth());
        int windowHeight = Math.max(1, m_window.getHeight());
        windowImage = new BufferedImage(windowWidth, windowHeight, BufferedImage.TYPE_INT_RGB);
        m_window.printAll(windowImage.getGraphics());
    }
    // prepare component image
    if (m_component == m_window) {
        image = windowImage;
    } else {
        // prepare location of component image on window image
        Point componentLocation;
        {
            Point p_component;
            if (m_component instanceof Applet) {
                // Applet reports "screen location" as (0,0), but we want location on "window"
                p_component = SwingUtils.getScreenLocation(m_component.getParent());
            } else {
                p_component = SwingUtils.getScreenLocation(m_component);
            }
            // continue
            Point p_window = SwingUtils.getScreenLocation(m_window);
            componentLocation = new Point(p_component.x - p_window.x, p_component.y - p_window.y);
        }
        // copy part of window image
        BufferedImage componentImage = new BufferedImage(componentWidth, componentHeight,
                BufferedImage.TYPE_INT_RGB);
        componentImage.getGraphics().drawImage(windowImage, 0, 0, componentWidth, componentHeight,
                componentLocation.x, componentLocation.y, componentLocation.x + componentWidth,
                componentLocation.y + componentHeight, m_window);
        image = componentImage;
    }
    // store image for top-level first
    m_componentImages.put(m_component, image);
    // do traverse
    SwingImageUtils.makeShotsHierarchy(m_component, m_componentImages, m_component);
    // convert images
    final Map<Component, Image> convertedImages = Maps.newHashMap();
    for (Component keyComponent : Collections.unmodifiableMap(m_componentImages).keySet()) {
        java.awt.Image image2 = m_componentImages.get(keyComponent);
        if (image2 != null) {
            convertedImages.put(keyComponent, SwingImageUtils.convertImage_AWT_to_SWT(image2));
        }
    }
    // draw decorations on OS X
    if (EnvironmentUtils.IS_MAC && m_window == m_component) {
        Image oldImage = convertedImages.get(m_component);
        convertedImages.put(m_component, SwingImageUtils.createOSXImage(m_window, oldImage));
        if (oldImage != null) {
            oldImage.dispose();
        }
    }
    // set images
    m_root.accept(new ObjectInfoVisitor() {
        @Override
        public void endVisit(ObjectInfo objectInfo) throws Exception {
            if (objectInfo instanceof AbstractComponentInfo) {
                AbstractComponentInfo componentInfo = (AbstractComponentInfo) objectInfo;
                Object componentObject = componentInfo.getComponentObject();
                Image image = convertedImages.get(componentObject);
                componentInfo.setImage(image);
            }
        }
    });
}

From source file:org.eclipse.wb.internal.swing.utils.SwingImageUtils.java

/**
 * @return the {@link java.awt.Image} of given {@link Component}. Must be called from AWT disp
 *         thread./*from w  w w  .  j  a  va  2  s.  c  o m*/
 */
static java.awt.Image createComponentShotAWT(final Component component) throws Exception {
    Assert.isNotNull(component);
    // prepare sizes
    final int componentWidth = component.getWidth();
    final int componentHeight = component.getHeight();
    final int imageWidth = Math.max(1, componentWidth);
    final int imageHeight = Math.max(1, componentHeight);
    // prepare empty image
    final BufferedImage componentImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
    // If actual size on component is zero, then we are done.
    if (componentWidth == 0 || componentHeight == 0) {
        return componentImage;
    }
    // some components like JLabel are transparent by default and printing it separately gives
    // bad results like invalid background color. The workaround is to set opacity property and
    // restore old value back when all done.
    ComponentShotConfigurator shotConfigurator = new ComponentShotConfigurator(component);
    try {
        // Linux only: it seems that printAll() should be invoked in AWT dispatch thread 
        // to prevent deadlocks between main thread and AWT event queue.
        // See also SwingUtils.invokeLaterAndWait().
        runInDispatchThread(new Runnable() {
            public void run() {
                component.printAll(componentImage.getGraphics());
            }
        });
    } finally {
        shotConfigurator.dispose();
    }
    // convert into SWT image
    return componentImage;
}

From source file:org.csml.tommo.sugar.modules.MappingQuality.java

private void writeImage2HTML(HTMLReportArchive report, LaneCoordinates laneCoordinates,
        TileNumeration tileNumeration) throws IOException {
    final MappingQualityTableModel model = new MappingQualityTableModel(this, laneCoordinates, tileNumeration);

    ZipOutputStream zip = report.zipFile();
    StringBuffer b = report.htmlDocument();
    StringBuffer d = report.dataDocument();

    int imgSize = Options.getHeatmapImageSize() + 1; // add one pixel for internal grid
    int width = imgSize * model.getColumnCount() + 1; // add one pixel for left border
    int topBottomSeparator = 50;
    if (model.getTopBottomSeparatorColumn() > 0) {
        width += topBottomSeparator; // add top bottom separator
    }// w  ww.  ja  va 2 s  . co  m
    int height = imgSize * model.getRowCount() + 1; // add one pixel for top border
    int yOffset = 10 * model.getTileNumeration().getCycleSize(); // space for column header
    int xOffset = 50; // space for row header
    BufferedImage fullImage = new BufferedImage(width + xOffset, height + yOffset, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = (Graphics2D) fullImage.getGraphics();
    Color headerBackground = new Color(0x00, 0x00, 0x80);
    Color headerForeground = Color.WHITE;

    // Do the headers
    d.append("#Tiles: ");

    d.append("\t");
    g2.setColor(headerBackground);
    g2.fillRect(0, height, width + xOffset, yOffset);
    g2.fillRect(width, 0, xOffset, height + yOffset);
    g2.setColor(headerForeground);
    g2.setFont(g2.getFont().deriveFont(7f).deriveFont(Font.BOLD));

    drawColumnHeader(g2, model, imgSize, topBottomSeparator, height, d);

    g2.setFont(g2.getFont().deriveFont(9f).deriveFont(Font.BOLD));
    drawRowHeader(g2, model, imgSize, width, xOffset);

    long before = System.currentTimeMillis();

    for (int r = 0; r < model.getRowCount(); r++) {
        int separator = 0;

        for (int c = 0; c < model.getColumnCount(); c++) {
            TileCoordinates tileCoordinate = model.getCoordinateAt(r, c);
            MappingQualityMatrix matrix = getMeanQualityMatrix(tileCoordinate);

            if (matrix != null) {
                if (r < MappingQualityMatrix.THRESHOLDS.length) {
                    ColorPaintScale paintScale = MappingQualityCellRenderer.getThresholdPaintScale();
                    BufferedImage image = (BufferedImage) matrix
                            .createBufferedImageForThreshold(MappingQualityMatrix.THRESHOLDS[r], paintScale);
                    g2.drawImage(image, 1 + imgSize * c + separator, 1 + imgSize * r,
                            imgSize * (c + 1) + separator, imgSize * (r + 1), 0, 0, image.getWidth(),
                            image.getHeight(), null);
                } else {
                    ColorPaintScale paintScale = MappingQualityCellRenderer.getAveragePaintScale();
                    BufferedImage image = (BufferedImage) matrix.createBufferedImage(paintScale);
                    g2.drawImage(image, 1 + imgSize * c + separator, 1 + imgSize * r,
                            imgSize * (c + 1) + separator, imgSize * (r + 1), 0, 0, image.getWidth(),
                            image.getHeight(), null);
                }

            } else {
                d.append("Missing matrix for: " + tileCoordinate + "\n");
            }
            if (c == model.getTopBottomSeparatorColumn()) {
                separator = topBottomSeparator;
            }
        }
    }

    g2.dispose();
    String imgFileName = "quality_matrix_" + laneCoordinates.getFlowCell() + "_" + laneCoordinates.getLane()
            + ".png";
    zip.putNextEntry(new ZipEntry(report.folderName() + "/Images/" + imgFileName));
    ImageIO.write(fullImage, "png", zip);
    b.append("<img src=\"Images/" + imgFileName + "\" alt=\"full image\">\n");

    long after = System.currentTimeMillis();
    d.append("Creating report time: " + (after - before));
}

From source file:com.digitalpersona.onetouch.ui.swing.sample.Enrollment.Dashboard.java

private void save_list() {
    List<Image> datas = fingerprint_list;
    List<S1_test.to_test> to_list = new ArrayList();
    for (Image to : datas) {

        BufferedImage buffered = new BufferedImage(jLabel1.getWidth(), jLabel1.getHeight(),
                Image.SCALE_DEFAULT);
        buffered.getGraphics().drawImage(to, 0, 0, null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {/*  ww  w. ja v  a2s  .c om*/
            ImageIO.write(buffered, "jpg", baos);
        } catch (IOException ex) {
            Logger.getLogger(Dlg_test.class.getName()).log(Level.SEVERE, null, ex);
        }
        byte[] imageInByte = baos.toByteArray();

        S1_test.to_test f = new S1_test.to_test(0, imageInByte);
        to_list.add(f);
    }
    S1_test.add_data(to_list);

}

From source file:tilt.image.page.Page.java

/**
 * Print the word shapes over the top of the original image
 * @param original the original raster to write to
 *///  w w w .  j  a v a 2s  .  c om
public void drawShapes(BufferedImage original) {
    Graphics g = original.getGraphics();
    for (int i = 0; i < lines.size(); i++) {
        Line l = lines.get(i);
        l.print(g, original.getRaster(), i + 1);
    }
}

From source file:algorithm.ImageImageFrameExpanding.java

/**
 * This method appends the payload image to the bottom of the carrier image.
 * Furthermore restoration information is added.
 * // w  w w .  jav  a 2s  .c  o m
 * @param carrier
 *            The file where the payload should be added
 * @param payload
 * @throws IOException
 */
private void append(File carrier, File payload) throws IOException {
    BufferedImage carrierImage = ImageIO.read(carrier);
    BufferedImage payloadImage = ImageIO.read(payload);
    if (carrierImage == null || payloadImage == null) {
        return;// "This wan't an image! Return."
    }
    BufferedImage outputImage = getOutputImage(carrierImage, payloadImage);
    BufferedImage metadataImage = getMetadataImage(carrier, payload);
    Graphics graphics = outputImage.getGraphics();
    graphics.drawImage(carrierImage, 0, 0, null);
    graphics.drawImage(payloadImage, 0, carrierImage.getHeight(), null);
    graphics.drawImage(metadataImage, 0, carrierImage.getHeight() + payloadImage.getHeight(), null);
    writeImage(carrier, outputImage);
}

From source file:com.pureinfo.tgirls.servlet.TestServlet.java

private BufferedImage getImg(File _temp, float _i) throws IOException {
    BufferedImage output;
    Image img = ImageIO.read(_temp);
    int width = img.getWidth(null);
    int height = img.getHeight(null);

    Float f = width * _i;/*from   w w w .  j av  a  2 s.c o m*/
    width = f.intValue();
    f = height * _i;
    height = f.intValue();

    output = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics g = output.getGraphics();
    g.drawImage(img, 0, 0, width, height, null);
    g.dispose();
    return output;
}

From source file:com.github.xmltopdf.JasperPdfGenerator.java

private void createDocument(List<String> templateNames, List<String> xmlFileNames, ByteArrayOutputStream os,
        DocType docType) {/*  w  w w . j a  v a 2 s .  c om*/
    List<JasperPrint> jasperPrints = new ArrayList<JasperPrint>();
    InputStream fileIs = null;
    InputStream stringIs = null;
    if (!xmlFileNames.isEmpty()) {
        xmlTag = XMLDoc.from(MergeXml.merge(xmlFileNames), true);
    }
    try {
        for (String templateName : templateNames) {
            try {
                fileIs = new FileInputStream(templateNames.get(0));
                String contents = applyVelocityTemplate(IOUtils.toString(fileIs, "UTF-8"));
                stringIs = IOUtils.toInputStream(contents, "UTF-8");
                JasperReport jasperReport = JasperCompileManager.compileReport(stringIs);
                jasperPrints.add(
                        JasperFillManager.fillReport(jasperReport, new HashMap(), new JREmptyDataSource()));
            } finally {
                IOUtils.closeQuietly(fileIs);
                IOUtils.closeQuietly(stringIs);
            }
        }
        JasperPrint jasperPrint = jasperPrints.get(0);
        for (int index = 1; index < jasperPrints.size(); index += 1) {
            List<JRPrintPage> pages = jasperPrints.get(index).getPages();
            for (JRPrintPage page : pages) {
                jasperPrint.addPage(page);
            }
        }
        switch (docType) {
        case PDF:
            JasperExportManager.exportReportToPdfStream(jasperPrint, os);
            break;
        case RTF:
            JRRtfExporter rtfExporter = new JRRtfExporter();
            rtfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            rtfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os);
            rtfExporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
            rtfExporter.exportReport();
            break;
        case XLS:
            JRXlsExporter xlsExporter = new JRXlsExporter();
            xlsExporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
            xlsExporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, os);
            xlsExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
            //                    xlsExporter.setParameter(JRXlsExporterParameter.IS_AUTO_DETECT_CELL_TYPE, Boolean.TRUE);
            xlsExporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
            xlsExporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
            xlsExporter.exportReport();
            break;
        case ODT:
            JROdtExporter odtExporter = new JROdtExporter();
            odtExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            odtExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os);
            odtExporter.exportReport();
            break;
        case PNG:
            BufferedImage pageImage = new BufferedImage((int) (jasperPrint.getPageWidth() * ZOOM_2X + 1),
                    (int) (jasperPrint.getPageHeight() * ZOOM_2X + 1), BufferedImage.TYPE_INT_RGB);
            JRGraphics2DExporter exporter = new JRGraphics2DExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, pageImage.getGraphics());
            exporter.setParameter(JRGraphics2DExporterParameter.ZOOM_RATIO, ZOOM_2X);
            exporter.setParameter(JRExporterParameter.PAGE_INDEX, Integer.valueOf(0));
            exporter.exportReport();
            ImageIO.write(pageImage, "png", os);
            break;
        case HTML:
            JRHtmlExporter htmlExporter = new JRHtmlExporter();
            htmlExporter.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint);
            htmlExporter.setParameter(JRHtmlExporterParameter.OUTPUT_STREAM, os);
            htmlExporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "img/");
            htmlExporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR, new java.io.File("img"));
            htmlExporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE);
            htmlExporter.setParameter(JRHtmlExporterParameter.ZOOM_RATIO, ZOOM_2X);
            htmlExporter.exportReport();
            break;
        case DOCX:
            JRDocxExporter docxExporter = new JRDocxExporter();
            docxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            docxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os);
            docxExporter.exportReport();
            break;
        default:
            break;
        }
    } catch (Exception ex) {
        LOG.error(this, ex, ex.getMessage());
    } finally {
        IOUtils.closeQuietly(os);
    }
}

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  w w w .jav a 2  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;
    }
}