Example usage for java.awt.image BufferedImage getTransparency

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

Introduction

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

Prototype

public int getTransparency() 

Source Link

Document

Returns the transparency.

Usage

From source file:com.springsecurity.plugin.util.ImageResizer.java

public BufferedImage scale(File icon, int targetWidth, int targetHeight) {
    BufferedImage ret = null;/*w  ww  .  ja  va2  s  . com*/
    if (icon.exists()) {
        try {
            BufferedImage img = ImageIO.read(icon);
            ret = img;
            int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB
                    : BufferedImage.TYPE_INT_ARGB;
            BufferedImage scratchImage = null;
            Graphics2D g2 = null;
            int w = img.getWidth();
            int h = img.getHeight();
            int prevW = w;
            int prevH = h;
            do {
                if (w > targetWidth) {
                    w /= 2;
                    w = (w < targetWidth) ? targetWidth : w;
                }
                if (h > targetHeight) {
                    h /= 2;
                    h = (h < targetHeight) ? targetHeight : h;
                }
                if (scratchImage == null) {
                    scratchImage = new BufferedImage(w, h, type);
                    g2 = scratchImage.createGraphics();
                }

                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g2.drawImage(ret, 0, 0, w, h, 0, 0, prevW, prevH, null);

                prevW = w;
                prevH = h;
                ret = scratchImage;
            } while (w != targetWidth || h != targetHeight);
            if (g2 != null) {
                g2.dispose();
            }
            if (targetWidth != ret.getWidth() || targetHeight != ret.getHeight()) {
                scratchImage = new BufferedImage(targetWidth, targetHeight, type);
                g2 = scratchImage.createGraphics();
                g2.drawImage(ret, 0, 0, null);
                g2.dispose();
                ret = scratchImage;
            }
        } catch (IOException e) {
        }
    }
    return ret;
}

From source file:ImageOpByRomain.java

/**
 * <p>/*www.j  a  v  a 2 s . c om*/
 * Return a new compatible image that contains a copy of the specified image.
 * This method ensures an image is compatible with the hardware, and therefore
 * optimized for fast blitting operations.
 * </p>
 * 
 * @see #createCompatibleImage(java.awt.image.BufferedImage)
 * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int)
 * @see #createCompatibleImage(int, int)
 * @see #createTranslucentCompatibleImage(int, int)
 * @see #loadCompatibleImage(java.net.URL)
 * @param image
 *            the image to copy into a new compatible image
 * @return a new compatible copy, with the same width and height and
 *         transparency and content, of <code>image</code>
 */
public static BufferedImage toCompatibleImage(BufferedImage image) {
    if (image.getColorModel().equals(CONFIGURATION.getColorModel())) {
        return image;
    }

    BufferedImage compatibleImage = CONFIGURATION.createCompatibleImage(image.getWidth(), image.getHeight(),
            image.getTransparency());
    Graphics g = compatibleImage.getGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();

    return compatibleImage;
}

From source file:PictureScaler.java

/**
 * Convenience method that returns a scaled instance of the
 * provided BufferedImage.// w  w  w  .  j av  a2 s . c o  m
 * 
 * 
 * @param img the original image to be scaled
 * @param targetWidth the desired width of the scaled instance,
 *    in pixels
 * @param targetHeight the desired height of the scaled instance,
 *    in pixels
 * @param hint one of the rendering hints that corresponds to
 *    RenderingHints.KEY_INTERPOLATION (e.g.
 *    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR,
 *    RenderingHints.VALUE_INTERPOLATION_BILINEAR,
 *    RenderingHints.VALUE_INTERPOLATION_BICUBIC)
 * @param progressiveBilinear if true, this method will use a multi-step
 *    scaling technique that provides higher quality than the usual
 *    one-step technique (only useful in down-scaling cases, where
 *    targetWidth or targetHeight is
 *    smaller than the original dimensions)
 * @return a scaled version of the original BufferedImage
 */
public BufferedImage getFasterScaledInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint,
        boolean progressiveBilinear) {
    int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB
            : BufferedImage.TYPE_INT_ARGB;
    BufferedImage ret = img;
    BufferedImage scratchImage = null;
    Graphics2D g2 = null;
    int w, h;
    int prevW = ret.getWidth();
    int prevH = ret.getHeight();
    boolean isTranslucent = img.getTransparency() != Transparency.OPAQUE;

    if (progressiveBilinear) {
        // Use multi-step technique: start with original size, then
        // scale down in multiple passes with drawImage()
        // until the target size is reached
        w = img.getWidth();
        h = img.getHeight();
    } else {
        // Use one-step technique: scale directly from original
        // size to target size with a single drawImage() call
        w = targetWidth;
        h = targetHeight;
    }

    do {
        if (progressiveBilinear && w > targetWidth) {
            w /= 2;
            if (w < targetWidth) {
                w = targetWidth;
            }
        }

        if (progressiveBilinear && h > targetHeight) {
            h /= 2;
            if (h < targetHeight) {
                h = targetHeight;
            }
        }

        if (scratchImage == null || isTranslucent) {
            // Use a single scratch buffer for all iterations
            // and then copy to the final, correctly-sized image
            // before returning
            scratchImage = new BufferedImage(w, h, type);
            g2 = scratchImage.createGraphics();
        }
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
        g2.drawImage(ret, 0, 0, w, h, 0, 0, prevW, prevH, null);
        prevW = w;
        prevH = h;

        ret = scratchImage;
    } while (w != targetWidth || h != targetHeight);

    if (g2 != null) {
        g2.dispose();
    }

    // If we used a scratch buffer that is larger than our target size,
    // create an image of the right size and copy the results into it
    if (targetWidth != ret.getWidth() || targetHeight != ret.getHeight()) {
        scratchImage = new BufferedImage(targetWidth, targetHeight, type);
        g2 = scratchImage.createGraphics();
        g2.drawImage(ret, 0, 0, null);
        g2.dispose();
        ret = scratchImage;
    }

    return ret;
}

From source file:edworld.pdfreader4humans.PDFReaderTest.java

private void assertImagesAreSimilar(InputStream expectedOutputStream, BufferedImage outputImage)
        throws IOException {
    try {//from  w w  w.  j  av  a  2s  .  c  om
        BufferedImage expectedOutputImage = ImageIO.read(expectedOutputStream);
        assertEquals(expectedOutputImage.getType(), outputImage.getType());
        assertEquals(expectedOutputImage.getWidth(), outputImage.getWidth());
        assertEquals(expectedOutputImage.getHeight(), outputImage.getHeight());
        assertEquals(expectedOutputImage.getTransparency(), outputImage.getTransparency());
        for (int k = 0; k < Math.max(outputImage.getWidth(), outputImage.getHeight()); k++) {
            int kX = k % outputImage.getWidth();
            int kY = k % outputImage.getHeight();
            int expectedColor = expectedOutputImage.getRGB(kX, kY);
            int actualColor = outputImage.getRGB(kX, kY);
            if ((expectedColor ^ 0xFFFFFF) == actualColor)
                expectedColor ^= 0xFFFFFF;
            assertEquals("Color should be the same at (" + k + "," + k + ").", expectedColor, actualColor);
        }
    } finally {
        expectedOutputStream.close();
    }
}

From source file:com.flexive.shared.media.impl.FxMediaNativeEngine.java

public static BufferedImage scale(BufferedImage bi, int width, int height) {
    BufferedImage bi2;//from   ww w  .  java 2s .  c  om
    int scaleWidth = bi.getWidth(null);
    int scaleHeight = bi.getHeight(null);
    double scaleX = (double) width / scaleWidth;
    double scaleY = (double) height / scaleHeight;
    double scale = Math.min(scaleX, scaleY);
    scaleWidth = (int) ((double) scaleWidth * scale);
    scaleHeight = (int) ((double) scaleHeight * scale);
    Image scaledImage;
    if (HEADLESS) {
        // create a new buffered image, don't rely on a local graphics system (headless mode)
        final int type;
        if (bi.getType() != BufferedImage.TYPE_CUSTOM) {
            type = bi.getType();
        } else if (bi.getAlphaRaster() != null) {
            // alpha channel available
            type = BufferedImage.TYPE_INT_ARGB;
        } else {
            type = BufferedImage.TYPE_INT_RGB;
        }
        bi2 = new BufferedImage(scaleWidth, scaleHeight, type);
    } else {
        GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getDefaultConfiguration();
        bi2 = gc.createCompatibleImage(scaleWidth, scaleHeight, bi.getTransparency());
    }
    Graphics2D g = bi2.createGraphics();
    if (scale < 0.3 && Math.max(scaleWidth, scaleHeight) < 500) {
        scaledImage = bi.getScaledInstance(scaleWidth, scaleHeight, Image.SCALE_SMOOTH);
        new ImageIcon(scaledImage).getImage();
        g.drawImage(scaledImage, 0, 0, scaleWidth, scaleHeight, null);
    } else {
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.drawImage(bi, 0, 0, scaleWidth, scaleHeight, null);
    }
    g.dispose();
    return bi2;
}

From source file:com.funambol.foundation.util.MediaUtils.java

/**
 * Rotates given buffered image by given amount of degree.
 * The valid degree values are 0, 90, 180, 270.
 * If the image is a jpg, the rotation is lossless, exif data are preserved
 * and image size is almost the same.//ww  w . j  av  a  2 s  . c  o m
 *
 * @param bufImage the buffered image
 * @param degree amount of degree to apply
 * @return a buffered image containing rotated image data
 * @throws PicturesException if amount of degree is invalid or if an
 *         IOException occurs
 */
private static BufferedImage rotateImage(BufferedImage bufImage, int degree)
        throws FileDataObjecyUtilsException {

    degree = degree % 360;
    int h;
    int w;

    switch (degree) {
    case 0:
    case 180:
        h = bufImage.getHeight();
        w = bufImage.getWidth();
        break;
    case 90:
    case 270:
        h = bufImage.getWidth();
        w = bufImage.getHeight();
        break;
    default:
        throw new FileDataObjecyUtilsException(
                "Error rotating image since the '" + degree + "' degree value is unsupported");
    }

    BufferedImage out = null;

    int bufImageType = bufImage.getType();
    if (BufferedImage.TYPE_BYTE_INDEXED == bufImageType || BufferedImage.TYPE_BYTE_BINARY == bufImageType) {

        IndexColorModel model = (IndexColorModel) bufImage.getColorModel();
        out = new BufferedImage(w, h, bufImage.getType(), model);

    } else if (BufferedImage.TYPE_CUSTOM == bufImageType) {

        // we don't know what type of image it can be

        // there's a bug in some VM that cause some PNG images to have 
        // type custom: this should take care of this issue

        //check if we need to have alpha channel
        boolean alpha = bufImage.getTransparency() != BufferedImage.OPAQUE;

        if (alpha) {
            // TYPE_INT_ARGB_PRE gives you smaller output images
            // than TYPE_INT_ARGB
            out = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
        } else {
            out = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        }

    } else {

        out = new BufferedImage(w, h, bufImage.getType());
    }

    Graphics2D g2d = out.createGraphics();

    Map renderingHints = new HashMap();

    renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);

    g2d.setRenderingHints(renderingHints);
    g2d.rotate(Math.toRadians(degree));

    switch (degree) {
    case 90:
        g2d.translate(0, -w);
        break;
    case 180:
        g2d.translate(-w, -h);
        break;
    case 270:
        g2d.translate(-h, 0);
        break;
    }

    g2d.drawImage(bufImage, null, 0, 0);
    g2d.dispose();

    return out;
}

From source file:com.flexive.shared.media.impl.FxMediaNativeEngine.java

/**
 * Rotate an image using the requested angle
 *
 * @param bufferedImage imeg to rotate/*  w  w w.ja va2  s  .c om*/
 * @param angle         angle to rotate
 * @return BufferedImage containing the rotation
 */
@SuppressWarnings({ "UnusedAssignment" })
private static BufferedImage rotate(BufferedImage bufferedImage, int angle) {
    angle = angle % 360;
    if (angle == 0)
        return bufferedImage;
    if (angle < 0)
        angle += 360;
    switch (angle) {
    case 90:
        BufferedImageOp rot90 = new AffineTransformOp(AffineTransform.getRotateInstance(Math.PI / 2.0,
                bufferedImage.getHeight() / 2.0, bufferedImage.getHeight() / 2.0),
                AffineTransformOp.TYPE_BILINEAR);
        BufferedImage img90 = new BufferedImage(bufferedImage.getHeight(), bufferedImage.getWidth(),
                bufferedImage.getType());
        return rot90.filter(bufferedImage, img90);
    case 180:
        BufferedImageOp rot180 = new AffineTransformOp(AffineTransform.getRotateInstance(Math.PI,
                bufferedImage.getWidth() / 2.0, bufferedImage.getHeight() / 2.0),
                AffineTransformOp.TYPE_BILINEAR);
        BufferedImage img180 = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(),
                bufferedImage.getType());
        return rot180.filter(bufferedImage, img180);
    case 270:
        BufferedImageOp rot270 = new AffineTransformOp(AffineTransform.getRotateInstance(-Math.PI / 2.0,
                bufferedImage.getWidth() / 2.0, bufferedImage.getWidth() / 2.0),
                AffineTransformOp.TYPE_BILINEAR);
        BufferedImage img270 = new BufferedImage(bufferedImage.getHeight(), bufferedImage.getWidth(),
                bufferedImage.getType());
        return rot270.filter(bufferedImage, img270);
    default:
        //rotate using a non-standard angle (have to draw a box around the image that can fit it)
        int box = (int) Math.sqrt(bufferedImage.getHeight() * bufferedImage.getHeight()
                + bufferedImage.getWidth() * bufferedImage.getWidth());
        BufferedImage imgFree = new BufferedImage(box, box, bufferedImage.getType());
        BufferedImage imgRet = new BufferedImage(box, box, bufferedImage.getType());
        Graphics2D g = imgFree.createGraphics();
        if (bufferedImage.getTransparency() == Transparency.OPAQUE) {
            //draw a white background on opaque images since they dont support transparency
            g.setBackground(Color.WHITE);
            g.clearRect(0, 0, box, box);
            Graphics2D gr = imgRet.createGraphics();
            gr.setBackground(Color.WHITE);
            gr.clearRect(0, 0, box, box);
            gr = null;
        }
        g.drawImage(bufferedImage, box / 2 - bufferedImage.getWidth() / 2,
                box / 2 - bufferedImage.getHeight() / 2, bufferedImage.getWidth(), bufferedImage.getHeight(),
                null);
        g = null;
        AffineTransform at = new AffineTransform();
        at.rotate(angle * Math.PI / 180.0, box / 2.0, box / 2.0);
        BufferedImageOp bio;
        bio = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
        return bio.filter(imgFree, imgRet);
    }
}

From source file:web.diva.server.model.SomClustering.SomClustImgGenerator.java

private BufferedImage rotateImage(BufferedImage masterImage, int angle) {
    int virtualAngle = getVirtualAngle(angle);
    Dimension size = new Dimension(masterImage.getWidth(), masterImage.getHeight());
    int masterWidth = masterImage.getWidth();
    int masterHeight = masterImage.getHeight();

    double x = 0; //masterWidth / 2.0;
    double y = 0; //masterHeight / 2.0;

    switch (virtualAngle) {
    case 0:/*from w w w  .j  a v  a  2s. c  o  m*/
        break;
    case 180:
        break;
    case 90:
    case 270:
        size = new Dimension(masterImage.getHeight(), masterImage.getWidth());
        x = (masterHeight - masterWidth) / 2.0;
        y = (masterWidth - masterHeight) / 2.0;
        break;
    }
    BufferedImage renderedImage = new BufferedImage(size.width, size.height, masterImage.getTransparency());
    Graphics2D g2d = renderedImage.createGraphics();

    AffineTransform at = AffineTransform.getTranslateInstance(x, y);

    at.rotate(Math.toRadians(virtualAngle), masterWidth / 2.0, masterHeight / 2.0);
    g2d.drawImage(masterImage, at, null);

    g2d.dispose();
    return renderedImage;
}

From source file:lucee.runtime.img.Image.java

/**
  * Convenience method that returns a scaled instance of the
  * provided {@code BufferedImage}.//from  w w w.  j ava2 s.c  om
  *
  * @param img the original image to be scaled
  * @param targetWidth the desired width of the scaled instance,
  *    in pixels
  * @param targetHeight the desired height of the scaled instance,
  *    in pixels
  * @param hint one of the rendering hints that corresponds to
  *    {@code RenderingHints.KEY_INTERPOLATION} (e.g.
  *    {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR},
  *    {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR},
  *    {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC})
  * @param higherQuality if true, this method will use a multi-step
  *    scaling technique that provides higher quality than the usual
  *    one-step technique (only useful in downscaling cases, where
  *    {@code targetWidth} or {@code targetHeight} is
  *    smaller than the original dimensions, and generally only when
  *    the {@code BILINEAR} hint is specified)
  * @return a scaled version of the original {@code BufferedImage}
  */
private BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint,
        boolean higherQuality) {
    // functionality not supported in java 1.4
    int transparency = Transparency.OPAQUE;
    try {
        transparency = img.getTransparency();
    } catch (Throwable t) {
    }
    int type = (transparency == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;

    BufferedImage ret = img;
    int w, h;
    if (higherQuality) {
        // Use multi-step technique: start with original size, then
        // scale down in multiple passes with drawImage()
        // until the target size is reached
        w = img.getWidth();
        h = img.getHeight();
    } else {
        // Use one-step technique: scale directly from original
        // size to target size with a single drawImage() call
        w = targetWidth;
        h = targetHeight;
    }

    do {
        if (higherQuality && w > targetWidth) {
            w /= 2;
            if (w < targetWidth) {
                w = targetWidth;
            }
        }

        if (higherQuality && h > targetHeight) {
            h /= 2;
            if (h < targetHeight) {
                h = targetHeight;
            }
        }

        BufferedImage tmp = new BufferedImage(w, h, type);
        Graphics2D g2 = tmp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
        g2.drawImage(ret, 0, 0, w, h, null);
        g2.dispose();

        ret = tmp;
    } while (w != targetWidth || h != targetHeight);

    return ret;
}

From source file:com.occamlab.te.parsers.ImageParser.java

private static Node processFrame(ImageReader reader, int frame, NodeList nodes, PrintWriter logger)
        throws Exception {
    if (nodes.getLength() == 0) {
        return null;
    }//from  www  .ja  v  a2 s .c o  m
    String formatName = reader.getFormatName().toLowerCase(); // 2011-09-08
                                                              // PwD
    BufferedImage image = reader.read(frame);

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // System.out.println(node.getLocalName());
            if (node.getLocalName().equals("type")) {
                node.setTextContent(formatName); // 2011-09-08 PwD was
                                                 // reader.getFormatName().toLowerCase()
            } else if (node.getLocalName().equals("height")) {
                node.setTextContent(Integer.toString(image.getHeight()));
            } else if (node.getLocalName().equals("width")) {
                node.setTextContent(Integer.toString(image.getWidth()));
            } else if (node.getLocalName().equals("metadata")) {
                try { // 2011--08-23 PwD
                    IIOMetadata metadata = reader.getImageMetadata(frame);
                    if (metadata != null) {
                        String format = ((Element) node).getAttribute("format");
                        if (format.length() == 0) {
                            format = metadata.getNativeMetadataFormatName();
                        }
                        Node tree = metadata.getAsTree(format);
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer t = tf.newTransformer();
                        t.transform(new DOMSource(tree), new DOMResult(node));
                    }
                } catch (javax.imageio.IIOException e) { // 2011--08-23 PwD
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc = db.newDocument();
                    String format = reader.getFormatName().toLowerCase();
                    String formatEltName = "javax_imageio_" + format + "_1.0";
                    Element formatElt = doc.createElement(formatEltName);
                    TransformerFactory tf = TransformerFactory.newInstance();
                    Transformer t = tf.newTransformer();
                    t.transform(new DOMSource(formatElt), new DOMResult(node));
                }
            } else if (node.getLocalName().equals("model")) {
                int imagetype = -1;
                String model = ((Element) node).getAttribute("value");
                if (model.equals("MONOCHROME")) {
                    imagetype = BufferedImage.TYPE_BYTE_BINARY;
                } else if (model.equals("GRAY")) {
                    imagetype = BufferedImage.TYPE_BYTE_GRAY;
                } else if (model.equals("RGB")) {
                    imagetype = BufferedImage.TYPE_3BYTE_BGR;
                } else if (model.equals("ARGB")) {
                    imagetype = BufferedImage.TYPE_4BYTE_ABGR;
                } else {
                    model = "CUSTOM";
                }
                ((Element) node).setAttribute("value", model);
                BufferedImage buffImage = image;
                if (image.getType() != imagetype && imagetype != -1) {
                    buffImage = new BufferedImage(image.getWidth(), image.getHeight(), imagetype);
                    Graphics2D g2 = buffImage.createGraphics();
                    ImageTracker tracker = new ImageTracker();
                    boolean done = g2.drawImage(image, 0, 0, tracker);
                    if (!done) {
                        while (!tracker.done) {
                            sleep(50);
                        }
                    }
                }
                processBufferedImage(buffImage, formatName, node.getChildNodes());
            } else if (node.getLocalName().equals("transparency")) { // 2011-08-24
                                                                     // PwD
                int transparency = image.getTransparency();
                String transparencyName = null;
                switch (transparency) {
                case Transparency.OPAQUE: {
                    transparencyName = "Opaque";
                    break;
                }
                case Transparency.BITMASK: {
                    transparencyName = "Bitmask";
                    break;
                }
                case Transparency.TRANSLUCENT: {
                    transparencyName = "Translucent";
                    break;
                }
                default: {
                    transparencyName = "Unknown";
                }
                }
                node.setTextContent(transparencyName);

            } else if (node.getLocalName().equals("base64Data")) { // 2011-09-08
                                                                   // PwD
                String base64Data = getBase64Data(image, formatName, node);
                node.setTextContent(base64Data);
            } else {
                logger.println("ImageParser Error: Invalid tag " + node.getNodeName());
            }
        }
    }
    return null;
}