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:be.fedict.eid.idp.sp.PhotoServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    response.setContentType("image/jpg");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    response.setHeader("Pragma", "no-cache, no-store"); // http 1.0
    response.setDateHeader("Expires", -1);
    ServletOutputStream out = response.getOutputStream();
    HttpSession session = request.getSession();

    byte[] photoData = (byte[]) session.getAttribute(PHOTO_SESSION_ATTRIBUTE);

    if (null != photoData) {
        BufferedImage photo = ImageIO.read(new ByteArrayInputStream(photoData));
        if (null == photo) {
            /*//from w w  w  .  ja  v a 2s  .  c om
             * In this case we render a photo containing some error message.
             */
            photo = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = (Graphics2D) photo.getGraphics();
            RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.setRenderingHints(renderingHints);
            graphics.setColor(Color.WHITE);
            graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1);
            graphics.setColor(Color.RED);
            graphics.setFont(new Font("Dialog", Font.BOLD, 20));
            graphics.drawString("Photo Error", 0, 200 / 2);
            graphics.dispose();
            ImageIO.write(photo, "jpg", out);
        } else {
            out.write(photoData);
        }
    }
    out.close();
}

From source file:be.fedict.eid.applet.service.PhotoServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    response.setContentType("image/jpg");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    response.setHeader("Pragma", "no-cache, no-store"); // http 1.0
    response.setDateHeader("Expires", -1);
    ServletOutputStream out = response.getOutputStream();
    HttpSession session = request.getSession();
    byte[] photoData = (byte[]) session.getAttribute(IdentityDataMessageHandler.PHOTO_SESSION_ATTRIBUTE);
    if (null != photoData) {
        BufferedImage photo = ImageIO.read(new ByteArrayInputStream(photoData));
        if (null == photo) {
            /*/*from w  w w.  jav a2s .co m*/
             * In this case we render a photo containing some error message.
             */
            photo = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = (Graphics2D) photo.getGraphics();
            RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.setRenderingHints(renderingHints);
            graphics.setColor(Color.WHITE);
            graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1);
            graphics.setColor(Color.RED);
            graphics.setFont(new Font("Dialog", Font.BOLD, 20));
            graphics.drawString("Photo Error", 0, 200 / 2);
            graphics.dispose();
            ImageIO.write(photo, "jpg", out);
        } else {
            out.write(photoData);
        }
    }
    out.close();
}

From source file:io.github.karols.hocr4j.PageRenderer.java

/**
 * Renders this page on a blank image.//from w w  w  .  j a v  a 2s  . c  o  m
 * The image is filled with the background color.
 *
 * @param page page to render
 * @return rendered image
 */
@Nonnull
public BufferedImage renderOnBlank(@Nonnull Page page) {
    Bounds pageBounds = page.getBounds().scale(scale);
    BufferedImage img = new BufferedImage(pageBounds.getRight(), pageBounds.getBottom(),
            BufferedImage.TYPE_INT_ARGB);
    Graphics g = img.getGraphics();
    g.setColor(backgroundColor);
    g.fillRect(0, 0, img.getWidth(), img.getHeight());
    renderOnTop(page, img);
    return img;
}

From source file:com.tremolosecurity.scale.totp.TotpController.java

@PostConstruct
public void init() {
    this.error = null;
    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();//from   w  ww  .j a  v  a  2  s  .  c o  m

    this.scaleTotpConfig = (ScaleTOTPConfigType) commonConfig.getScaleConfig();

    this.login = request.getRemoteUser();

    UnisonUserData userData;
    try {
        userData = this.scaleSession.loadUserFromUnison(this.login,
                new AttributeData(scaleTotpConfig.getServiceConfiguration().getLookupAttributeName(),
                        scaleTotpConfig.getUiConfig().getDisplayNameAttribute(),
                        scaleTotpConfig.getAttributeName()));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    }

    this.user = userData.getUserObj();

    this.displayName = userData.getUserObj().getDisplayName();

    ScaleAttribute scaleAttr = userData.getUserObj().getAttrs().get(scaleTotpConfig.getAttributeName());
    if (scaleAttr == null) {
        if (logger.isDebugEnabled())
            logger.debug("no sattribute");
        this.error = "Token not found";
        return;
    }

    this.encryptedToken = scaleAttr.getValue();

    try {
        byte[] decryptionKeyBytes = Base64.decodeBase64(scaleTotpConfig.getDecryptionKey().getBytes("UTF-8"));
        SecretKey decryptionKey = new SecretKeySpec(decryptionKeyBytes, 0, decryptionKeyBytes.length, "AES");

        Gson gson = new Gson();
        Token token = gson.fromJson(new String(Base64.decodeBase64(this.encryptedToken.getBytes("UTF-8"))),
                Token.class);
        byte[] iv = org.bouncycastle.util.encoders.Base64.decode(token.getIv());
        IvParameterSpec spec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, decryptionKey, spec);

        String decryptedJSON = new String(
                cipher.doFinal(Base64.decodeBase64(token.getEncryptedRequest().getBytes("UTF-8"))));

        if (logger.isDebugEnabled())
            logger.debug(decryptedJSON);

        TOTPKey totp = gson.fromJson(decryptedJSON, TOTPKey.class);

        this.otpURL = "otpauth://totp/" + totp.getUserName() + "@" + totp.getHost() + "?secret="
                + totp.getSecretKey();

    } catch (Exception e) {
        e.printStackTrace();
        this.error = "Could not decrypt token";
    }

    try {
        int size = 250;
        Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix byteMatrix = qrCodeWriter.encode(this.otpURL, BarcodeFormat.QR_CODE, size, size, hintMap);
        int CrunchifyWidth = byteMatrix.getWidth();
        BufferedImage image = new BufferedImage(CrunchifyWidth, CrunchifyWidth, BufferedImage.TYPE_INT_RGB);
        image.createGraphics();

        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth);
        graphics.setColor(Color.BLACK);

        for (int i = 0; i < CrunchifyWidth; i++) {
            for (int j = 0; j < CrunchifyWidth; j++) {
                if (byteMatrix.get(i, j)) {
                    graphics.fillRect(i, j, 1, 1);
                }
            }
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ImageIO.write(image, "png", baos);

        this.encodedQRCode = new String(Base64.encodeBase64(baos.toByteArray()));
    } catch (Exception e) {
        e.printStackTrace();
        this.error = "Could not encode QR Code";
    }

}

From source file:org.alfresco.po.share.util.SiteUtil.java

/**
 * This method create in Temp directory jpg file for uploading.
 * //from   w  w  w .  ja  v  a2s . co  m
 * @param jpgName String
 * @return File object for created Image.
 */
public File prepareJpg(String jpgName) {
    BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();
    g.drawString("Test Publish file.", 5, 10);
    g.drawString(jpgName, 5, 50);
    try {
        File jpgFile = File.createTempFile(jpgName, ".jpg");
        ImageIO.write(image, "jpg", jpgFile);
        return jpgFile;
    } catch (IOException e) {
        e.printStackTrace();
    }
    throw new SkipException("Can't create JPG file");
}

From source file:org.jcurl.core.swing.RockLocationDisplayBase.java

public void exportPng(File dst) throws IOException {
    final BufferedImage img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
    final Graphics2D g2 = (Graphics2D) img.getGraphics();
    {/*from   w  ww .  ja  v a2  s .  co  m*/
        final Map hints = new HashMap();
        hints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        hints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        hints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        hints.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        hints.put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
        hints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.addRenderingHints(hints);
    }
    this.paintComponent(g2);
    g2.dispose();
    if (!dst.getName().endsWith(".png"))
        dst = new File(dst.getName() + ".png");
    ImageIO.write(img, "png", dst);
}

From source file:org.apache.cocoon.reading.ImageReader.java

protected void processStream(InputStream inputStream) throws IOException, ProcessingException {
    if (hasTransform()) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("image " + ((width == 0) ? "?" : Integer.toString(width)) + "x"
                    + ((height == 0) ? "?" : Integer.toString(height)) + " expires: " + expires);
        }/*w w w .ja  v  a  2  s. co m*/

        /*
         * NOTE (SM):
         * Due to Bug Id 4502892 (which is found in *all* JVM implementations from
         * 1.2.x and 1.3.x on all OS!), we must buffer the JPEG generation to avoid
         * that connection resetting by the peer (user pressing the stop button,
         * for example) crashes the entire JVM (yes, dude, the bug is *that* nasty
         * since it happens in JPEG routines which are native!)
         * I'm perfectly aware of the huge memory problems that this causes (almost
         * doubling memory consuption for each image and making the GC work twice
         * as hard) but it's *far* better than restarting the JVM every 2 minutes
         * (since this is the average experience for image-intensive web application
         * such as an image gallery).
         * Please, go to the <a href="http://developer.java.sun.com/developer/bugParade/bugs/4502892.html">Sun Developers Connection</a>
         * and vote this BUG as the one you would like fixed sooner rather than
         * later and all this hack will automagically go away.
         * Many deep thanks to Michael Hartle <mhartle@hartle-klug.com> for tracking
         * this down and suggesting the workaround.
         *
         * UPDATE (SM):
         * This appears to be fixed on JDK 1.4
         */

        try {
            byte content[] = readFully(inputStream);
            ImageIcon icon = new ImageIcon(content);
            BufferedImage original = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                    BufferedImage.TYPE_INT_RGB);
            BufferedImage currentImage = original;
            currentImage.getGraphics().drawImage(icon.getImage(), 0, 0, null);

            if (width > 0 || height > 0) {
                double ow = icon.getImage().getWidth(null);
                double oh = icon.getImage().getHeight(null);

                if (usePercent) {
                    if (width > 0) {
                        width = Math.round((int) (ow * width) / 100);
                    }
                    if (height > 0) {
                        height = Math.round((int) (oh * height) / 100);
                    }
                }

                AffineTransformOp filter = new AffineTransformOp(getTransform(ow, oh, width, height),
                        AffineTransformOp.TYPE_BILINEAR);
                WritableRaster scaledRaster = filter.createCompatibleDestRaster(currentImage.getRaster());

                filter.filter(currentImage.getRaster(), scaledRaster);

                currentImage = new BufferedImage(original.getColorModel(), scaledRaster, true, null);
            }

            if (null != grayscaleFilter) {
                grayscaleFilter.filter(currentImage, currentImage);
            }

            if (null != colorFilter) {
                colorFilter.filter(currentImage, currentImage);
            }

            // JVM Bug handling
            if (JVMBugFixed) {
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                JPEGEncodeParam p = encoder.getDefaultJPEGEncodeParam(currentImage);
                p.setQuality(this.quality[0], true);
                encoder.setJPEGEncodeParam(p);
                encoder.encode(currentImage);
            } else {
                ByteArrayOutputStream bstream = new ByteArrayOutputStream();
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bstream);
                JPEGEncodeParam p = encoder.getDefaultJPEGEncodeParam(currentImage);
                p.setQuality(this.quality[0], true);
                encoder.setJPEGEncodeParam(p);
                encoder.encode(currentImage);
                out.write(bstream.toByteArray());
            }

            out.flush();
        } catch (ImageFormatException e) {
            throw new ProcessingException(
                    "Error reading the image. " + "Note that only JPEG images are currently supported.");
        } finally {
            // Bugzilla Bug 25069, close inputStream in finally block
            // this will close inputStream even if processStream throws
            // an exception
            inputStream.close();
        }
    } else {
        // only read the resource - no modifications requested
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("passing original resource");
        }
        super.processStream(inputStream);
    }
}

From source file:org.openstreetmap.gui.jmapviewer.Tile.java

/**
 * Tries to get tiles of a lower or higher zoom level (one or two level
 * difference) from cache and use it as a placeholder until the tile has
 * been loaded./*from   w  w w.  j a va 2s  .com*/
 */
public void loadPlaceholderFromCache(TileCache cache) {
    BufferedImage tmpImage = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) tmpImage.getGraphics();
    // g.drawImage(image, 0, 0, null);
    for (int zoomDiff = 1; zoomDiff < 5; zoomDiff++) {
        // first we check if there are already the 2^x tiles
        // of a higher detail level
        int zoom_high = zoom + zoomDiff;
        if (zoomDiff < 3 && zoom_high <= JMapViewer.MAX_ZOOM) {
            int factor = 1 << zoomDiff;
            int xtile_high = xtile << zoomDiff;
            int ytile_high = ytile << zoomDiff;
            double scale = 1.0 / factor;
            g.setTransform(AffineTransform.getScaleInstance(scale, scale));
            int paintedTileCount = 0;
            for (int x = 0; x < factor; x++) {
                for (int y = 0; y < factor; y++) {
                    Tile tile = cache.getTile(source, xtile_high + x, ytile_high + y, zoom_high);
                    if (tile != null && tile.isLoaded()) {
                        paintedTileCount++;
                        tile.paint(g, x * SIZE, y * SIZE);
                    }
                }
            }
            if (paintedTileCount == factor * factor) {
                image = tmpImage;
                return;
            }
        }

        int zoom_low = zoom - zoomDiff;
        if (zoom_low >= JMapViewer.MIN_ZOOM) {
            int xtile_low = xtile >> zoomDiff;
            int ytile_low = ytile >> zoomDiff;
            int factor = (1 << zoomDiff);
            double scale = factor;
            AffineTransform at = new AffineTransform();
            int translate_x = (xtile % factor) * SIZE;
            int translate_y = (ytile % factor) * SIZE;
            at.setTransform(scale, 0, 0, scale, -translate_x, -translate_y);
            g.setTransform(at);
            Tile tile = cache.getTile(source, xtile_low, ytile_low, zoom_low);
            if (tile != null && tile.isLoaded()) {
                tile.paint(g, 0, 0);
                image = tmpImage;
                return;
            }
        }
    }
}

From source file:com.yanbang.portal.controller.PortalController.java

/**
 * ???//from  w ww .  j  a v  a2s  .c  o  m
 * 
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(params = "action=handleRnd")
public void handleRnd(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0L);
    response.setContentType("image/jpeg");
    BufferedImage image = new BufferedImage(65, 25, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();
    g.setColor(Color.GRAY);
    g.fillRect(0, 0, 65, 25);
    g.setColor(Color.yellow);
    Font font = new Font("", Font.BOLD, 20);
    g.setFont(font);
    Random r = new Random();
    String rnd = "";
    int ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 5, 18);
    g.setColor(Color.red);
    ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 20, 18);
    g.setColor(Color.blue);
    ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 35, 18);
    g.setColor(Color.green);
    ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 50, 18);
    request.getSession().setAttribute("RND", rnd);
    ServletOutputStream out = response.getOutputStream();
    out.write(ImageUtil.imageToBytes(image, "gif"));
    out.flush();
    out.close();
}

From source file:org.stanwood.nwn2.gui.view.UIIconView.java

@Override
public void paintUIObject(Graphics g) {
    int x = getX();
    int y = getY();
    try {/*from   w  w w. j  ava2s .c om*/
        BufferedImage img = getIconManager().getIcon(icon.getImg());
        int width = getWidth();
        int height = getHeight();

        if (img.getHeight() != height && img.getWidth() != width) {
            Image newImg = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics ig = img.getGraphics();
            ig.drawImage(newImg, 0, 0, null);
        }

        if (icon.getColor() != null) {
            Color colour = getColor(icon.getColor());
            for (int w = 0; w < img.getWidth(); w++) {
                for (int h = 0; h < img.getHeight(); h++) {
                    Color rgb = ColorUtil.blend(new Color(img.getRGB(w, h)), colour);
                    img.setRGB(w, h, rgb.getRGB());
                }
            }
        }

        g.drawImage(img, x, y, null);
    } catch (Exception e) {
        log.error(e.getMessage());
        drawMissingIcon(x, y, getWidth(), getHeight(), g);
    }
}