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 boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor,
        ImageObserver observer);

Source Link

Document

Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.

Usage

From source file:ch.rasc.downloadchart.DownloadChartServlet.java

private static void handleJpg(HttpServletResponse response, byte[] imageData, Integer width, Integer height,
        String filename, JpegOptions options) throws IOException {

    response.setContentType("image/jpeg");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".jpg\";");

    BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData));

    Dimension newDimension = calculateDimension(image, width, height);
    int imgWidth = image.getWidth();
    int imgHeight = image.getHeight();
    if (newDimension != null) {
        imgWidth = newDimension.width;//from  ww  w .j  ava 2 s .c om
        imgHeight = newDimension.height;
    }

    BufferedImage newImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = newImage.createGraphics();
    g.drawImage(image, 0, 0, imgWidth, imgHeight, Color.BLACK, null);
    g.dispose();

    if (newDimension != null) {
        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);
    }

    try (ImageOutputStream ios = ImageIO.createImageOutputStream(response.getOutputStream())) {
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");
        ImageWriter writer = iter.next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        if (options != null && options.quality != null && options.quality != 0 && options.quality != 100) {
            iwp.setCompressionQuality(options.quality / 100f);
        } else {
            iwp.setCompressionQuality(1);
        }
        writer.setOutput(ios);
        writer.write(null, new IIOImage(newImage, null, null), iwp);
        writer.dispose();
    }
}

From source file:de.mprengemann.intellij.plugin.androidicons.util.ImageUtils.java

private static BufferedImage ensureJpgCompatibility(BufferedImage image) {
    BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = imageRGB.createGraphics();
    g2.drawImage(image, 0, 0, imageRGB.getWidth(), imageRGB.getHeight(), Color.WHITE, null);
    g2.dispose();/*from  w w  w  .  j a  va  2  s.  c o m*/
    return imageRGB;
}

From source file:net.dv8tion.jda.utils.AvatarUtil.java

private static BufferedImage resize(BufferedImage originalImage) {
    BufferedImage resizedImage = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_RGB);
    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(originalImage, 0, 0, SIZE, SIZE, Color.white, null);

    g.dispose();/*from ww  w  . j ava  2s  . com*/

    return resizedImage;
}

From source file:com.gst.infrastructure.documentmanagement.data.ImageData.java

public void resizeImage(InputStream in, OutputStream out, int maxWidth, int maxHeight) throws IOException {

    BufferedImage src = ImageIO.read(in);
    if (src.getWidth() <= maxWidth && src.getHeight() <= maxHeight) {
        out.write(getContent());//  www .ja  v  a 2  s  . c om
        return;
    }
    float widthRatio = (float) src.getWidth() / maxWidth;
    float heightRatio = (float) src.getHeight() / maxHeight;
    float scaleRatio = widthRatio > heightRatio ? widthRatio : heightRatio;

    // TODO(lindahl): Improve compressed image quality (perhaps quality
    // ratio)

    int newWidth = (int) (src.getWidth() / scaleRatio);
    int newHeight = (int) (src.getHeight() / scaleRatio);
    int colorModel = fileExtension == ContentRepositoryUtils.IMAGE_FILE_EXTENSION.JPEG
            ? BufferedImage.TYPE_INT_RGB
            : BufferedImage.TYPE_INT_ARGB;
    BufferedImage target = new BufferedImage(newWidth, newHeight, colorModel);
    Graphics2D g = target.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.drawImage(src, 0, 0, newWidth, newHeight, Color.BLACK, null);
    g.dispose();
    ImageIO.write(target, fileExtension != null ? fileExtension.getValueWithoutDot() : "jpeg", out);
}

From source file:au.com.gaiaresources.bdrs.controller.test.TestDataCreator.java

private byte[] getAndScaleImageData(int targetWidth, int targetHeight, File file) throws IOException {
    if (file == null) {
        return null;
    }/*from w  w  w .j  a v  a2s. c  om*/

    BufferedImage sourceImage = ImageIO.read(file);
    BufferedImage targetImage;
    if (targetWidth > -1 && targetHeight > -1) {
        // Resize the image as required to fit the space
        targetImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2_scaled = targetImage.createGraphics();
        // Better scaling
        g2_scaled.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BICUBIC);

        g2_scaled.setBackground(Color.WHITE);
        g2_scaled.clearRect(0, 0, targetWidth, targetHeight);

        int sourceWidth = sourceImage.getWidth();
        int sourceHeight = sourceImage.getHeight();

        double widthRatio = (double) targetWidth / (double) sourceWidth;
        double heightRatio = (double) targetHeight / (double) targetHeight;

        if (heightRatio > widthRatio) {
            int scaledHeight = (int) Math.round(widthRatio * sourceHeight);
            g2_scaled.drawImage(sourceImage, 0, (targetImage.getHeight() - scaledHeight) / 2,
                    targetImage.getWidth(), scaledHeight, g2_scaled.getBackground(), null);
        } else {
            int scaledWidth = (int) Math.round(heightRatio * sourceWidth);
            g2_scaled.drawImage(sourceImage, (targetImage.getWidth() - scaledWidth) / 2, 0, scaledWidth,
                    targetImage.getHeight(), new Color(0, 0, 0, 255), null);
        }
    } else {
        targetImage = sourceImage;
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream(targetWidth * targetHeight);
    ImageIO.write(targetImage, "png", baos);
    baos.flush();
    byte[] data = baos.toByteArray();
    baos.close();

    return data;
}

From source file:org.apache.ofbiz.common.CommonEvents.java

public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) {
    try {//from   w  ww  . j a  v  a2 s .c  o m
        Delegator delegator = (Delegator) request.getAttribute("delegator");
        final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"),
                "default");
        final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha",
                "captcha." + captchaSizeConfigName, delegator);
        final String[] captchaSizeConfigs = captchaSizeConfig.split("\\|");
        final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), ""); // this is used to uniquely identify in the user session the attribute where the captcha code for the last captcha for the form is stored

        final int fontSize = Integer.parseInt(captchaSizeConfigs[0]);
        final int height = Integer.parseInt(captchaSizeConfigs[1]);
        final int width = Integer.parseInt(captchaSizeConfigs[2]);
        final int charsToPrint = UtilProperties.getPropertyAsInteger("captcha", "captcha.code_length", 6);
        final char[] availableChars = EntityUtilProperties
                .getPropertyValue("captcha", "captcha.characters", delegator).toCharArray();

        //It is possible to pass the font size, image width and height with the request as well
        Color backgroundColor = Color.gray;
        Color borderColor = Color.DARK_GRAY;
        Color textColor = Color.ORANGE;
        Color circleColor = new Color(160, 160, 160);
        Font textFont = new Font("Arial", Font.PLAIN, fontSize);
        int circlesToDraw = 6;
        float horizMargin = 20.0f;
        double rotationRange = 0.7; // in radians
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics2D g = (Graphics2D) bufferedImage.getGraphics();

        g.setColor(backgroundColor);
        g.fillRect(0, 0, width, height);

        //Generating some circles for background noise
        g.setColor(circleColor);
        for (int i = 0; i < circlesToDraw; i++) {
            int circleRadius = (int) (Math.random() * height / 2.0);
            int circleX = (int) (Math.random() * width - circleRadius);
            int circleY = (int) (Math.random() * height - circleRadius);
            g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2);
        }
        g.setColor(textColor);
        g.setFont(textFont);

        FontMetrics fontMetrics = g.getFontMetrics();
        int maxAdvance = fontMetrics.getMaxAdvance();
        int fontHeight = fontMetrics.getHeight();

        String captchaCode = RandomStringUtils.random(6, availableChars);

        float spaceForLetters = -horizMargin * 2 + width;
        float spacePerChar = spaceForLetters / (charsToPrint - 1.0f);

        for (int i = 0; i < captchaCode.length(); i++) {

            // this is a separate canvas used for the character so that
            // we can rotate it independently
            int charWidth = fontMetrics.charWidth(captchaCode.charAt(i));
            int charDim = Math.max(maxAdvance, fontHeight);
            int halfCharDim = (charDim / 2);

            BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB);
            Graphics2D charGraphics = charImage.createGraphics();
            charGraphics.translate(halfCharDim, halfCharDim);
            double angle = (Math.random() - 0.5) * rotationRange;
            charGraphics.transform(AffineTransform.getRotateInstance(angle));
            charGraphics.translate(-halfCharDim, -halfCharDim);
            charGraphics.setColor(textColor);
            charGraphics.setFont(textFont);

            int charX = (int) (0.5 * charDim - 0.5 * charWidth);
            charGraphics.drawString("" + captchaCode.charAt(i), charX,
                    ((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent()));

            float x = horizMargin + spacePerChar * (i) - charDim / 2.0f;
            int y = ((height - charDim) / 2);

            g.drawImage(charImage, (int) x, y, charDim, charDim, null, null);

            charGraphics.dispose();
        }
        // Drawing the image border
        g.setColor(borderColor);
        g.drawRect(0, 0, width - 1, height - 1);
        g.dispose();
        response.setContentType("image/jpeg");
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
        HttpSession session = request.getSession();
        Map<String, String> captchaCodeMap = UtilGenerics.checkMap(session.getAttribute("_CAPTCHA_CODE_"));
        if (captchaCodeMap == null) {
            captchaCodeMap = new HashMap<String, String>();
            session.setAttribute("_CAPTCHA_CODE_", captchaCodeMap);
        }
        captchaCodeMap.put(captchaCodeId, captchaCode);
    } catch (Exception ioe) {
        Debug.logError(ioe.getMessage(), module);
    }
    return "success";
}