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:com.pronoiahealth.olhie.server.services.BookCoverImageService.java

/**
 * Create the front cover//w w w  .j av  a2 s.  com
 * 
 * @param coverId
 * @param logoBytes
 * @param authorStr
 * @param titleStr
 * @param textColor
 *            - ex. #FFFFFF
 * @param width
 * @param height
 * @param type
 *            - ex. BufferedImage.TYPE_INT_ARGB
 * @param imgFormat
 *            - ex. ImageFormat.IMAGE_FORMAT_PNG
 * @return
 * @throws Exception
 */
public byte[] createFrontCover(String coverId, byte[] logoBytes, String authorStr, String titleStr,
        String spineColor, String authorTextColor, String titleTextColor, int width, int height, int type,
        ImageFormat imgFormat, int maxColors) throws Exception {

    Graphics2D g = null;

    try {
        // Front cover first
        // Read in base cover image
        BufferedImage coverImg = Imaging.getBufferedImage(coverMap.get(coverId));

        // Resize cover image to the basic 300 X 400 for front cover
        BufferedImage frontCoverImg = resize(coverImg, 300, 400, type);
        g = (Graphics2D) frontCoverImg.getGraphics();

        // Draw logo if present
        if (logoBytes != null && logoBytes.length > 0) {
            // Resize logo to 200x100
            BufferedImage logoImg = Imaging.getBufferedImage(logoBytes);
            BufferedImage outLogo = null;
            int logoHeight = logoImg.getHeight();
            int logoWidth = logoImg.getWidth();

            if (logoHeight > 100 || logoWidth > 200) {
                outLogo = this.resize(logoImg, logoWidth > 200 ? 200 : logoWidth,
                        logoHeight > 100 ? 100 : logoHeight, type);
            } else {
                outLogo = logoImg;
            }

            // Add to coverImg
            g.drawImage(outLogo, 32, 25, null);
        }

        // Add spine if present
        if (spineColor != null && spineColor.length() > 0) {
            g.setColor(Color.decode(spineColor));
            g.fillRect(0, 0, 2, frontCoverImg.getHeight());
        }

        // Add author if present
        if (authorStr != null && authorStr.length() > 0) {
            // Add author text to image
            BufferedImage authorTextImg = createText(40, 220, authorStr, authorTextColor, false, authorFontMap,
                    type);
            g.drawImage(authorTextImg, 30, 215, null);
        }

        // Add title if present
        if (titleStr != null && titleStr.length() > 0) {
            BufferedImage titleTextImg = createText(100, 220, titleStr, titleTextColor, false, titleFontMap,
                    type);
            g.drawImage(titleTextImg, 30, 240, null);
        }

        // If the requested size is not 300X400 convert the image
        BufferedImage outImg = null;
        if (width != 300 || height != 400) {
            outImg = resize(frontCoverImg, width, height, type);
        } else {
            outImg = frontCoverImg;
        }

        // Do we want a PNG with a fixed number of colors
        if (maxColors >= 2 && imgFormat == ImageFormat.IMAGE_FORMAT_PNG) {
            outImg = ImageUtils.reduce32(outImg, maxColors);
        }

        // Return bytes
        Map<String, Object> params = new HashMap<String, Object>();
        byte[] outBytes = Imaging.writeImageToBytes(outImg, imgFormat, params);
        return outBytes;
    } finally {
        if (g != null) {
            g.dispose();
        }
    }
}

From source file:org.squale.squaleweb.applicationlayer.action.export.ppt.PPTData.java

/**
 * Convert a html code to an image// ww  w. jav  a2s. c  om
 * 
 * @param html html to convert
 * @return html converted to png
 * @throws IOException if error
 * @throws PPTGeneratorException 
 */
protected byte[] htmlToImage(String html) throws IOException, PPTGeneratorException {
    try {
        JEditorPane editor = new JEditorPane();
        editor.setContentType("text/html");
        editor.setText(html);
        editor.setSize(editor.getPreferredSize());
        editor.addNotify();
        LOGGER.debug("Panel is built");
        BufferedImage bufferSave = new BufferedImage(editor.getPreferredSize().width,
                editor.getPreferredSize().height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics g = bufferSave.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, editor.getPreferredSize().width, editor.getPreferredSize().height);
        editor.paint(g);
        LOGGER.debug("graphics is drawn");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(bufferSave, "png", out);
        return out.toByteArray();
    } catch (HeadlessException e) {
        LOGGER.error("X Server no initialized or -Djava.awt.headless=true not set !");
        throw new PPTGeneratorException("X Server no initialized or -Djava.awt.headless=true not set !");
    }
}

From source file:au.org.ala.biocache.web.MapController.java

@RequestMapping(value = "/occurrences/legend", method = RequestMethod.GET)
public void pointLegendImage(
        @RequestParam(value = "colourby", required = false, defaultValue = "0") Integer colourby,
        @RequestParam(value = "width", required = false, defaultValue = "50") Integer widthObj,
        @RequestParam(value = "height", required = false, defaultValue = "50") Integer heightObj,
        HttpServletResponse response) {/*  w  w  w . j a v  a  2s  .c o m*/
    try {
        int width = widthObj.intValue();
        int height = heightObj.intValue();

        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) img.getGraphics();

        if (colourby != null) {
            int colour = 0xFF000000 | colourby.intValue();
            Color c = new Color(colour);
            g.setPaint(c);

        } else {
            g.setPaint(Color.blue);
        }

        g.fillOval(0, 0, width, width);

        g.dispose();

        response.setContentType("image/png");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(img, "png", outputStream);
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(outputStream.toByteArray());
        outStream.flush();
        outStream.close();

    } catch (Exception e) {
        logger.error("Unable to write image", e);
    }
}

From source file:org.squale.squaleweb.applicationlayer.action.export.ppt.PPTData.java

/**
 * Add an image with a html code without change its dimension
 * /*from  w w w. j a  v a  2  s.c o m*/
 * @param slideToSet slide to set
 * @param html html code
 * @param x horizontal position
 * @param y vertical position
 * @throws IOException if error
 * @throws PPTGeneratorException 
 */
protected void addHtmlPicture(Slide slideToSet, String html, int x, int y)
        throws IOException, PPTGeneratorException {
    try {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        if (!ge.isHeadlessInstance()) {
            LOGGER.warn("Runtime is not configured for supporting graphiv manipulation !");
        }
        JEditorPane editor = new JEditorPane();
        editor.setContentType("text/html");
        editor.setText(html);
        LOGGER.debug("Editor pane is built");
        editor.setSize(editor.getPreferredSize());
        editor.addNotify(); // Serveur X requis
        LOGGER.debug("Panel rendering is done");
        BufferedImage bufferSave = new BufferedImage(editor.getPreferredSize().width,
                editor.getPreferredSize().height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics g = bufferSave.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, editor.getPreferredSize().width, editor.getPreferredSize().height);
        editor.paint(g);
        LOGGER.debug("graphics is drawn");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(bufferSave, "png", out);
        LOGGER.debug("image is written");
        addPicture(slideToSet, out.toByteArray(),
                new Rectangle(x, y, editor.getPreferredSize().width, editor.getPreferredSize().height));
        LOGGER.debug("image is added");
    } catch (HeadlessException e) {
        LOGGER.error("X Server no initialized or -Djava.awt.headless=true not set !");
        throw new PPTGeneratorException("X Server no initialized or -Djava.awt.headless=true not set !");
    }
}

From source file:org.sbs.util.ImageCompress.java

public String compressPic() {
    try {/*from w w  w .  j  a v  a 2s .  co m*/
        // ?
        file = new File(inputDir + inputFileName);
        if (!file.exists()) {
            return "";
        }
        Image img = ImageIO.read(file);
        // ??
        if (img.getWidth(null) == -1) {
            System.out.println(" can't read,retry!" + "<BR>");
            return "no";
        } else {
            int newWidth;
            int newHeight;
            // ?
            if (this.proportion == true) {
                // ?
                double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1;
                double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1;
                // ?
                double rate = rate1 > rate2 ? rate1 : rate2;
                newWidth = (int) (((double) img.getWidth(null)) / rate);
                newHeight = (int) (((double) img.getHeight(null)) / rate);
            } else {
                newWidth = outputWidth; // 
                newHeight = outputHeight; // 
            }
            BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);

            /*
             * Image.SCALE_SMOOTH  ?  ?? 
             */
            tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0,
                    null);
            FileOutputStream out = new FileOutputStream(outputDir + outputFileName);
            // JPEGImageEncoder??
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(tag);
            out.close();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return "ok";
}

From source file:HiResCoordTest.java

private Shape3D createLabel(String szText, float x, float y, float z) {
    BufferedImage bufferedImage = new BufferedImage(50, 20, BufferedImage.TYPE_INT_RGB);
    Graphics g = bufferedImage.getGraphics();
    g.setColor(Color.white);/*from   ww w  . j  a v  a  2 s.co m*/
    g.drawString(szText, 10, 10);

    ImageComponent2D imageComponent2D = new ImageComponent2D(ImageComponent2D.FORMAT_RGB, bufferedImage);
    imageComponent2D.setCapability(ImageComponent.ALLOW_IMAGE_READ);
    imageComponent2D.setCapability(ImageComponent.ALLOW_SIZE_READ);

    // create the Raster for the image
    javax.media.j3d.Raster renderRaster = new javax.media.j3d.Raster(new Point3f(x, y, z),
            javax.media.j3d.Raster.RASTER_COLOR, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(),
            imageComponent2D, null);

    return new Shape3D(renderRaster);
}

From source file:com.pronoiahealth.olhie.server.services.BookCoverImageService.java

/**
 * Create an image that contains text//from w  w  w .j  a  va  2s .com
 * 
 * @param height
 * @param width
 * @param text
 * @param textColor
 * @param center
 * @param fontMap
 * @param type
 * @return
 */
private BufferedImage createText(int height, int width, String text, String textColor, boolean center,
        Map<TextAttribute, Object> fontMap, int type) {
    BufferedImage img = new BufferedImage(width, height, type);
    Graphics2D g2d = null;
    try {
        g2d = (Graphics2D) img.getGraphics();

        // Create attributed text
        AttributedString txt = new AttributedString(text, fontMap);

        // Set graphics color
        g2d.setColor(Color.decode(textColor));

        // Create a new LineBreakMeasurer from the paragraph.
        // It will be cached and re-used.
        AttributedCharacterIterator paragraph = txt.getIterator();
        int paragraphStart = paragraph.getBeginIndex();
        int paragraphEnd = paragraph.getEndIndex();
        FontRenderContext frc = g2d.getFontRenderContext();
        LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(paragraph, frc);

        // Set break width to width of Component.
        float breakWidth = (float) width;
        float drawPosY = 0;
        // Set position to the index of the first character in the
        // paragraph.
        lineMeasurer.setPosition(paragraphStart);

        // Get lines until the entire paragraph has been displayed.
        while (lineMeasurer.getPosition() < paragraphEnd) {
            // Retrieve next layout. A cleverer program would also cache
            // these layouts until the component is re-sized.
            TextLayout layout = lineMeasurer.nextLayout(breakWidth);

            // Compute pen x position. If the paragraph is right-to-left we
            // will align the TextLayouts to the right edge of the panel.
            // Note: drawPosX is always where the LEFT of the text is
            // placed.
            float drawPosX = layout.isLeftToRight() ? 0 : breakWidth - layout.getAdvance();

            if (center == true) {
                double xOffSet = (width - layout.getBounds().getWidth()) / 2;
                drawPosX = drawPosX + new Float(xOffSet);
            }

            // Move y-coordinate by the ascent of the layout.
            drawPosY += layout.getAscent();

            // Draw the TextLayout at (drawPosX, drawPosY).
            layout.draw(g2d, drawPosX, drawPosY);

            // Move y-coordinate in preparation for next layout.
            drawPosY += layout.getDescent() + layout.getLeading();
        }
    } finally {
        if (g2d != null) {
            g2d.dispose();
        }
    }
    return img;
}

From source file:pl.edu.icm.visnow.lib.basic.viewers.Viewer2D.Display2DPanel.java

public void writeImage(File file) {
    BufferedImage img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
    dontWrite = true;/*from w w w.ja v  a  2s  .  c om*/
    paintComponent(img.getGraphics());
    dontWrite = false;

    String ext = FilenameUtils.getExtension(file.getAbsolutePath()).toLowerCase();

    try {
        if (ext.equals("jpg") || ext.equals("jpeg")) {
            ImageUtilities.writeJpeg(img, 1.0f, file);
        } else if (ext.equals("png")) {
            ImageUtilities.writePng(img, file);
        } else if (ext.equals("gif")) {
            ImageUtilities.writeGif(img, file);
        } else if (ext.equals("tif") || ext.equals("tiff")) {
            ImageUtilities.writeTiff(img, TiffConstants.TIFF_COMPRESSION_UNCOMPRESSED, file);
        } else if (ext.equals("bmp")) {
            ImageUtilities.writeBmp(img, file);
        } else if (ext.equals("pcx")) {
            ImageUtilities.writePcx(img, file);
        } else {
            throw new IllegalArgumentException("Invalid file extension " + ext);
        }
    } catch (IOException e) {
        System.out.println("I/O exception for " + file.getAbsolutePath());
    }

}

From source file:org.fcrepo.localservices.imagemanip.ImageManipulation.java

/**
 * Method automatically called by browser to handle image manipulations.
 * /*from  w  w  w .j a  v a 2s  .c o m*/
 * @param req
 *        Browser request to servlet res Response sent back to browser after
 *        image manipulation
 * @throws IOException
 *         If an input or output exception occurred ServletException If a
 *         servlet exception occurred
 */
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    System.setProperty("java.awt.headless", "true");
    // collect all possible parameters for servlet
    String url = req.getParameter("url");
    String op = req.getParameter("op");
    String newWidth = req.getParameter("newWidth");
    String brightAmt = req.getParameter("brightAmt");
    String zoomAmt = req.getParameter("zoomAmt");
    String wmText = req.getParameter("wmText");
    String cropX = req.getParameter("cropX");
    String cropY = req.getParameter("cropY");
    String cropWidth = req.getParameter("cropWidth");
    String cropHeight = req.getParameter("cropHeight");
    String convertTo = req.getParameter("convertTo");
    if (convertTo != null) {
        convertTo = convertTo.toLowerCase();
    }
    try {
        if (op == null) {
            throw new ServletException("op parameter not specified.");
        }
        String outputMimeType;
        // get the image via url and put it into the ImagePlus processor.
        BufferedImage img = getImage(url);
        // do watermarking stuff
        if (op.equals("watermark")) {
            if (wmText == null) {
                throw new ServletException("Must specify wmText.");
            }
            Graphics g = img.getGraphics();
            int fontSize = img.getWidth() * 3 / 100;
            if (fontSize < 10) {
                fontSize = 10;
            }
            g.setFont(new Font("Lucida Sans", Font.BOLD, fontSize));
            FontMetrics fm = g.getFontMetrics();
            int stringWidth = (int) fm.getStringBounds(wmText, g).getWidth();
            int x = img.getWidth() / 2 - stringWidth / 2;
            int y = img.getHeight() - fm.getHeight();
            g.setColor(new Color(180, 180, 180));
            g.fill3DRect(x - 10, y - fm.getHeight() - 4, stringWidth + 20, fm.getHeight() + 12, true);
            g.setColor(new Color(100, 100, 100));
            g.drawString(wmText, x + 2, y + 2);
            g.setColor(new Color(240, 240, 240));
            g.drawString(wmText, x, y);
        }
        ImageProcessor ip = new ImagePlus("temp", img).getProcessor();
        // if the inputMimeType is image/gif, need to convert to RGB in any case
        if (inputMimeType.equals("image/gif")) {
            ip = ip.convertToRGB();
            alreadyConvertedToRGB = true;
        }
        // causes scale() and resize() to do bilinear interpolation
        ip.setInterpolate(true);
        if (!op.equals("convert")) {
            if (op.equals("resize")) {
                ip = resize(ip, newWidth);
            } else if (op.equals("zoom")) {
                ip = zoom(ip, zoomAmt);
            } else if (op.equals("brightness")) {
                ip = brightness(ip, brightAmt);
            } else if (op.equals("watermark")) {
                // this is now taken care of beforehand (see above)
            } else if (op.equals("grayscale")) {
                ip = grayscale(ip);
            } else if (op.equals("crop")) {
                ip = crop(ip, cropX, cropY, cropWidth, cropHeight);
            } else {
                throw new ServletException("Invalid operation: " + op);
            }
            outputMimeType = inputMimeType;
        } else {
            if (convertTo == null) {
                throw new ServletException("Neither op nor convertTo was specified.");
            }
            if (convertTo.equals("jpg") || convertTo.equals("jpeg")) {
                outputMimeType = "image/jpeg";
            } else if (convertTo.equals("gif")) {
                outputMimeType = "image/gif";
            } else if (convertTo.equals("tiff")) {
                outputMimeType = "image/tiff";
            } else if (convertTo.equals("bmp")) {
                outputMimeType = "image/bmp";
            } else if (convertTo.equals("png")) {
                outputMimeType = "image/png";
            } else {
                throw new ServletException("Invalid format: " + convertTo);
            }
        }
        res.setContentType(outputMimeType);
        BufferedOutputStream out = new BufferedOutputStream(res.getOutputStream());
        outputImage(ip, out, outputMimeType);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                e.getClass().getName() + ": " + e.getMessage());
    }
}

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

@Override
public void actionPerformed(ActionEvent e) {

    NoteTableTab activeTab = getActiveTab();
    if (e.getActionCommand() != null && activeTab != null) {
        if (e.getActionCommand().equals("Copy")) {
            activeTab.transferSelection(NoteTableTab.TRANSFER_TYPE.COPY_TO_INTERNAL_CLIPBOARD);
        } else if (e.getActionCommand().equals("BBCopy")) {
            activeTab.transferSelection(NoteTableTab.TRANSFER_TYPE.CLIPBOARD_BB);
        } else if (e.getActionCommand().equals("BBCopy_Village")) {
            activeTab.copyVillagesAsBBCodes();
        } else if (e.getActionCommand().equals("Cut")) {
            activeTab.transferSelection(NoteTableTab.TRANSFER_TYPE.CUT_TO_INTERNAL_CLIPBOARD);
        } else if (e.getActionCommand().equals("Paste")) {
            activeTab.transferSelection(NoteTableTab.TRANSFER_TYPE.FROM_INTERNAL_CLIPBOARD);
        } else if (e.getActionCommand().equals("Delete")) {
            activeTab.deleteSelection(true);
        } else if (e.getActionCommand().equals("Delete_Village")) {
            activeTab.deleteVillagesFromNotes();
        } else 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  . j a  v  a 2  s. co m*/
            g.dispose();
            TexturePaint paint = new TexturePaint(back,
                    new Rectangle2D.Double(0, 0, back.getWidth(), back.getHeight()));
            jxSearchPane.setBackgroundPainter(new MattePainter(paint));
            jxSearchPane.setVisible(true);
        }
    }
}