Example usage for java.awt.image BufferedImage createGraphics

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

Introduction

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

Prototype

public Graphics2D createGraphics() 

Source Link

Document

Creates a Graphics2D , which can be used to draw into this BufferedImage .

Usage

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  w w  .  ja v a 2s . 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.suren.autotest.web.framework.log.Image4SearchLog.java

@Around("execution(* org.suren.autotest.web.framework.core.ElementSearchStrategy.search*(..))")
public Object hello(ProceedingJoinPoint joinPoint) throws Throwable {
    Object[] args = joinPoint.getArgs();

    Object res = joinPoint.proceed(args);
    WebDriver driver = engine.getDriver();
    if (res instanceof WebElement && driver instanceof TakesScreenshot) {
        TakesScreenshot shot = (TakesScreenshot) driver;

        File file = shot.getScreenshotAs(OutputType.FILE);
        BufferedImage bufImg = ImageIO.read(file);

        try {/*from w  w w  .j ava  2  s.c  o m*/
            WebElement webEle = (WebElement) res;
            Point loc = webEle.getLocation();
            Dimension size = webEle.getSize();

            Graphics2D g = bufImg.createGraphics();
            g.setColor(Color.red);
            g.drawRect(loc.getX(), loc.getY(), size.getWidth(), size.getHeight());
        } catch (StaleElementReferenceException e) {
            //
        }

        File elementSearchImageFile = new File(outputDir,
                progressIdentify + "_" + System.currentTimeMillis() + ".png");
        try (OutputStream output = new FileOutputStream(elementSearchImageFile)) {
            ImageIO.write(bufImg, "gif", output);
            elementSearchImageFileList.add(elementSearchImageFile);
            animatedGifEncoder.addFrame(bufImg);
        }
    }

    return res;
}

From source file:TexturedPanel.java

/**
 * Creates a new TexturePaint using the provided colors.
 *//* w  ww  . j av a  2 s.  c om*/
private void setupDefaultPainter(Color foreground, Color background) {
    if (foreground == null || background == null) {
        ourPainter = null;
        return;
    }

    BufferedImage buff = new BufferedImage(6, 6, BufferedImage.TYPE_INT_ARGB_PRE);

    Graphics2D g2 = buff.createGraphics();

    g2.setColor(background);
    g2.fillRect(0, 0, 6, 6);

    g2.setColor(foreground);
    g2.drawLine(0, 2, 6, 2);
    g2.drawLine(0, 5, 6, 5);

    ourPainter = new TexturePaint(buff, new Rectangle(0, 0, 6, 6));

    g2.dispose();
}

From source file:TexturedPanel.java

/**
 * Creates a new TexturePaint using the provided image.
 *///  w  w  w  .ja v a2s .co m
private void setupImagePainter(Image texture) {
    if (texture == null) {
        ourPainter = null;
        return;
    }

    int w = texture.getWidth(this);
    int h = texture.getHeight(this);

    if (w <= 0 || h <= 0) {
        ourPainter = null;
        return;
    }

    BufferedImage buff = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);

    Graphics2D g2 = buff.createGraphics();
    g2.drawImage(texture, 0, 0, this);
    ourPainter = new TexturePaint(buff, new Rectangle(0, 0, w, h));

    g2.dispose();
}

From source file:TexturedPanel.java

/**
 * Creates a new TexturePaint using the provided icon.
 *//*from  w  ww.ja va  2 s.  c o  m*/
private void setupIconPainter(Icon texture) {
    if (texture == null) {
        ourPainter = null;
        return;
    }

    int w = texture.getIconWidth();
    int h = texture.getIconHeight();

    if (w <= 0 || h <= 0) {
        ourPainter = null;
        return;
    }

    BufferedImage buff = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);

    Graphics2D g2 = buff.createGraphics();
    texture.paintIcon(this, g2, 0, 0);
    ourPainter = new TexturePaint(buff, new Rectangle(0, 0, w, h));

    g2.dispose();
}

From source file:com.salesmanager.core.util.ProductImageUtil.java

public BufferedImage resize(BufferedImage image, int width, int height) {
    int type = image.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : image.getType();
    BufferedImage resizedImage = new BufferedImage(width, height, type);
    Graphics2D g = resizedImage.createGraphics();
    g.setComposite(AlphaComposite.Src);
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.drawImage(image, 0, 0, width, height, null);
    g.dispose();/*from w  w  w.  ja  v  a 2 s  .com*/
    return resizedImage;
}

From source file:com.igormaznitsa.jhexed.renders.svg.SVGImage.java

public BufferedImage rasterize(final int width, final int height, final int imageType) throws IOException {
    final BufferedImage result = new BufferedImage(width, height, imageType);
    final float xfactor = (float) width / getSVGWidth();
    final float yfactor = (float) height / getSVGHeight();

    final Graphics2D g = result.createGraphics();

    processAntialias(this.quality, g);
    g.setTransform(AffineTransform.getScaleInstance(xfactor, yfactor));
    this.svgGraphicsNode.primitivePaint(g);

    g.dispose();/*from  www  .ja v  a2 s.c  om*/
    return result;
}

From source file:org.n52.oxf.render.sos.TimeSeriesMapChartRenderer.java

/**
 * @param observationCollection/*  w w  w  .  j  av a 2s.  co  m*/
 * @param screenW
 * @param screenH
 * @param bbox
 * @param selectedFeatures
 *        the Features of Interest for which a chart shall be renderered.
 */
public StaticVisualization renderLayer(OXFFeatureCollection observationCollection, ParameterContainer paramCon,
        int screenW, int screenH, IBoundingBox bbox, Set<OXFFeature> selectedFeatures) {
    if (selectedFeaturesCache == null) {
        selectedFeaturesCache = selectedFeatures;
    }

    // before starting to render --> run garbageCollection
    Runtime.getRuntime().gc();
    LOGGER.info("Garbage Collection done.");
    // --

    String[] observedProperties;
    // which observedProperty has been used?:
    ParameterShell observedPropertyPS = paramCon.getParameterShellWithServiceSidedName("observedProperty");
    if (observedPropertyPS.hasMultipleSpecifiedValues()) {
        observedProperties = observedPropertyPS.getSpecifiedTypedValueArray(String[].class);
    } else if (observedPropertyPS.hasSingleSpecifiedValue()) {
        observedProperties = new String[] { (String) observedPropertyPS.getSpecifiedValue() };
    } else {
        throw new IllegalArgumentException("no observedProperties found.");
    }

    // find tuples:
    if (obsValues4FOI == null) {
        obsValues4FOI = new ObservationSeriesCollection(observationCollection, selectedFeaturesCache,
                observedProperties, true);
    }

    ContextBoundingBox contextBBox = new ContextBoundingBox(bbox);

    BufferedImage image = new BufferedImage(screenW, screenH, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = image.createGraphics();

    // draw white background:
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, screenW, screenH);

    g.setColor(Color.BLACK);

    for (OXFFeature chartFeature : selectedFeaturesCache) {

        //
        // CACHING: create Plot for each "chart feature" and add it to the cache:
        //
        if (!chartCache.containsKey(chartFeature)) {
            Map<ITimePosition, ObservedValueTuple> timeMap = obsValues4FOI.getAllTuples(chartFeature);

            // draw a chart if there are tuples for the chartFeature available:
            if (timeMap != null) {
                XYPlot chart = drawChart4FOI(chartFeature.getID(), timeMap);
                chartCache.put(chartFeature, chart);
            }
        }

        //
        // draw the plots (which are in the cache):
        //
        Point pRealWorld = (Point) chartFeature.getGeometry();

        java.awt.Point pScreen = ContextBoundingBox.realworld2Screen(contextBBox.getActualBBox(), screenW,
                screenH, new Point2D.Double(pRealWorld.getCoordinate().x, pRealWorld.getCoordinate().y));
        XYPlot cachedPlot = (XYPlot) chartCache.get(chartFeature);

        // if there is a plot in the cache for the chartFeature -> draw it:
        if (cachedPlot != null) {
            cachedPlot.getRangeAxis().setRange((Double) obsValues4FOI.getMinimum(0),
                    (Double) obsValues4FOI.getMaximum(0));

            cachedPlot.draw(g,
                    new Rectangle2D.Float(pScreen.x + X_SHIFT, pScreen.y + Y_SHIFT, CHART_WIDTH, CHART_HEIGHT),
                    null, null, null);
        } else {
            g.drawString("No data available", pScreen.x + X_SHIFT, pScreen.y + Y_SHIFT);
        }

        // draw point of feature:
        g.fillOval(pScreen.x - (FeatureGeometryRenderer.DOT_SIZE_POINT / 2),
                pScreen.y - (FeatureGeometryRenderer.DOT_SIZE_POINT / 2),
                FeatureGeometryRenderer.DOT_SIZE_POINT, FeatureGeometryRenderer.DOT_SIZE_POINT);

    }

    return new StaticVisualization(image);
}

From source file:com.salesmanager.core.util.ProductImageUtil.java

private BufferedImage createCompatibleImage(BufferedImage image) {
    GraphicsConfiguration gc = BufferedImageGraphicsConfig.getConfig(image);
    int w = image.getWidth();
    int h = image.getHeight();
    BufferedImage result = gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
    Graphics2D g2 = result.createGraphics();
    g2.drawRenderedImage(image, null);//from w w  w .  ja va 2  s.c  om
    g2.dispose();
    return result;
}

From source file:de.brazzy.nikki.model.ImageReader.java

/**
 * Scales image to given size, preserving aspec ratio
 * //from  w w  w.  j av  a2 s . c om
 * @param toWidth
 *            width to scale to
 * @param paintBorder
 *            whether to paint an etched border around the image
 * @param isThumbnail
 *            if true, faster low-quality scaling will be used
 */
public byte[] scale(int toWidth, boolean paintBorder, boolean isThumbnail)
        throws IOException, LLJTranException {
    readMainImage();

    int toHeight = heightForWidth(mainImage, toWidth);

    BufferedImageOp op = isThumbnail ? new ThumpnailRescaleOp(toWidth, toHeight)
            : new ResampleOp(toWidth, toHeight);

    BufferedImage scaledImage = op.filter(mainImage, null);
    if (paintBorder) {
        Graphics2D g = scaledImage.createGraphics();
        g.setPaintMode();
        new EtchedBorder(EtchedBorder.RAISED, Color.LIGHT_GRAY, Color.DARK_GRAY).paintBorder(null, g, 0, 0,
                toWidth, toHeight);
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ImageIO.write(scaledImage, "jpg", out);
    return adjustForRotation(out.toByteArray());
}