Example usage for java.awt.image BufferedImage getWidth

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

Introduction

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

Prototype

public int getWidth() 

Source Link

Document

Returns the width of the BufferedImage .

Usage

From source file:com.simiacryptus.mindseye.applications.ArtistryUtil.java

/**
 * Paint circles./* ww w.  java2  s .  c o  m*/
 *
 * @param canvas the canvas
 * @param scale  the scale
 */
public static void paint_Circles(final Tensor canvas, final int scale) {
    BufferedImage originalImage = canvas.toImage();
    BufferedImage newImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = (Graphics2D) newImage.getGraphics();
    IntStream.range(0, 10000).forEach(i -> {
        Random random = new Random();
        int positionX = random.nextInt(originalImage.getWidth());
        int positionY = random.nextInt(originalImage.getHeight());
        int width = 1 + random.nextInt(2 * scale);
        int height = 1 + random.nextInt(2 * scale);
        DoubleStatistics[] stats = { new DoubleStatistics(), new DoubleStatistics(), new DoubleStatistics() };
        canvas.coordStream(false).filter(c -> {
            int[] coords = c.getCoords();
            int x = coords[0];
            int y = coords[1];
            double relX = Math.pow(1 - 2 * ((double) (x - positionX) / width), 2);
            double relY = Math.pow(1 - 2 * ((double) (y - positionY) / height), 2);
            return relX + relY < 1.0;
        }).forEach(c -> stats[c.getCoords()[2]].accept(canvas.get(c)));
        graphics.setStroke(new Stroke() {
            @Override
            public Shape createStrokedShape(final Shape p) {
                return null;
            }
        });
        graphics.setColor(new Color((int) stats[0].getAverage(), (int) stats[1].getAverage(),
                (int) stats[2].getAverage()));
        graphics.fillOval(positionX, positionY, width, height);
    });
    canvas.set(Tensor.fromRGB(newImage));
}

From source file:com.sun.socialsite.util.ImageUtil.java

/**
 * Convenience method that returns a scaled instance of the
 * provided {@code BufferedImage}./* ww w.j  a  va2 s .com*/
 *
 * NOTE: Adapted from code at
 * {@link http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html}.
 *
 * @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 static BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight,
        Object hint, boolean higherQuality) {
    int type = BufferedImage.TYPE_INT_ARGB;
    BufferedImage ret = (BufferedImage) 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.t3.image.ImageUtil.java

public static void clearImage(BufferedImage image) {

    if (image == null) {
        return;//from  w ww. ja  v a  2s .c o m
    }

    Graphics2D g = null;
    try {

        g = (Graphics2D) image.getGraphics();
        Composite oldComposite = g.getComposite();

        g.setComposite(AlphaComposite.Clear);

        g.fillRect(0, 0, image.getWidth(), image.getHeight());

        g.setComposite(oldComposite);
    } finally {
        if (g != null) {
            g.dispose();
        }
    }
}

From source file:fr.gael.dhus.datastore.processing.impl.ProcessingUtils.java

/**
 * Cut the quicklook that have a big width/height ratio.
 * Each sub-part is dispatched on multiple bands.
 *
 * @param quick_look the quick_look to be cut
 * @param max_ratio the maximum ratio between quick_look width and height.
 * @param margin the margin between each band. default 5.
 *//*  w w w  .  j  a v a 2 s.  c o  m*/
public static RenderedImage cutQuickLook(RenderedImage input_image, double max_ratio, int margin) {
    ColorModel color_model = input_image.getColorModel();
    if ((color_model == null) && (input_image.getSampleModel() != null)) {
        color_model = ColorRenderer.createColorModel(input_image.getSampleModel());
    }

    BufferedImage quick_look;
    try {
        quick_look = PlanarImage.wrapRenderedImage(input_image).getAsBufferedImage(
                new Rectangle(input_image.getWidth(), input_image.getHeight()), color_model);
    } catch (Exception e) {
        logger.error("Problem getting buffered image.", e);
        throw new IllegalArgumentException("Problem getting buffered image", e);
    }

    if ((quick_look != null) && ((quick_look.getWidth() > 0) && (quick_look.getHeight() > 0))) {
        //Compute width/height ratio
        int ql_width = quick_look.getWidth();
        int ql_height = quick_look.getHeight();
        int ratio = (int) Math.sqrt(Math.max(ql_width, ql_height) / Math.min(ql_width, ql_height));

        //Check if the quicklook has a strong width/height ratio
        if ((ratio < max_ratio) || (ratio <= 1))
            return PlanarImage.wrapRenderedImage(quick_look);

        /**
         * Cut the wider side (width or height) into "ratio" bands.
         * Ex: If height = 3 * width then we cut 3 bands along columns
         *     So height' = height / 3   (extract 1 band / 3 from height)
         *        width'  = width  * 3   (dispatch 3 bands along lines)
         */
        int width = ql_width; //width of the bands
        int height = ql_height; //height of the bands

        if (ql_width < ql_height) //cut along height
        {
            width = (ql_width + margin) * ratio;
            height = ql_height / ratio;
        } else //cut along width
        {
            width = ql_width / ratio;
            height = (ql_height + margin) * ratio;
        }

        //Dispatch the sub-parts
        BufferedImage quick_look_cut = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = quick_look_cut.createGraphics();

        for (int k = 0; k < ratio; k++) {
            BufferedImage ql_band = null;
            //Dispatch on columns
            if (ql_width < ql_height) {
                ql_band = quick_look.getSubimage(0, (k * ql_height) / ratio, ql_width, ql_height / ratio);
                g2.drawImage(ql_band, null, k * (ql_width + margin), 0);
            }
            //Dispatch on lines
            else {
                ql_band = quick_look.getSubimage((k * ql_width) / ratio, 0, ql_width / ratio, ql_height);
                g2.drawImage(ql_band, null, 0, k * (ql_height + margin));
            }
        } //for each band

        g2.dispose();
        return PlanarImage.wrapRenderedImage(quick_look_cut);
    }
    return PlanarImage.wrapRenderedImage(quick_look);
}

From source file:ImageUtils.java

/**
 * Creates a <code>BufferedImage</code> from an <code>Image</code>. This method can
 * function on a completely headless system. This especially includes Linux and Unix systems
 * that do not have the X11 libraries installed, which are required for the AWT subsystem to
 * operate. The resulting image will be smoothly scaled using bilinear filtering.
 * //from   ww w .jav a  2 s .  c o  m
 * @param source The image to convert
 * @param w The desired image width
 * @param h The desired image height
 * @return The converted image
 * @param type  int
 */
public static BufferedImage createHeadlessSmoothBufferedImage(BufferedImage source, int type, int width,
        int height) {
    if (type == ImageUtils.IMAGE_PNG && hasAlpha(source)) {
        type = BufferedImage.TYPE_INT_ARGB;
    } else {
        type = BufferedImage.TYPE_INT_RGB;
    }

    BufferedImage dest = new BufferedImage(width, height, type);

    int sourcex;
    int sourcey;

    double scalex = (double) width / source.getWidth();
    double scaley = (double) height / source.getHeight();

    int x1;
    int y1;

    double xdiff;
    double ydiff;

    int rgb;
    int rgb1;
    int rgb2;

    for (int y = 0; y < height; y++) {
        sourcey = y * source.getHeight() / dest.getHeight();
        ydiff = scale(y, scaley) - sourcey;

        for (int x = 0; x < width; x++) {
            sourcex = x * source.getWidth() / dest.getWidth();
            xdiff = scale(x, scalex) - sourcex;

            x1 = Math.min(source.getWidth() - 1, sourcex + 1);
            y1 = Math.min(source.getHeight() - 1, sourcey + 1);

            rgb1 = getRGBInterpolation(source.getRGB(sourcex, sourcey), source.getRGB(x1, sourcey), xdiff);
            rgb2 = getRGBInterpolation(source.getRGB(sourcex, y1), source.getRGB(x1, y1), xdiff);

            rgb = getRGBInterpolation(rgb1, rgb2, ydiff);

            dest.setRGB(x, y, rgb);
        }
    }

    return dest;
}

From source file:com.simiacryptus.mindseye.applications.ArtistryUtil.java

/**
 * Paint low res.//from w ww  .  j  av a  2  s  . c o  m
 *
 * @param canvas the canvas
 * @param scale  the scale
 */
public static void paint_LowRes(final Tensor canvas, final int scale) {
    BufferedImage originalImage = canvas.toImage();
    canvas.set(Tensor
            .fromRGB(TestUtil.resize(TestUtil.resize(originalImage, originalImage.getWidth() / scale, true),
                    originalImage.getWidth(), originalImage.getHeight())));
}

From source file:ImageUtils.java

/**
 * Creates a <code>BufferedImage</code> from an <code>Image</code>. This method can
 * function on a completely headless system. This especially includes Linux and Unix systems
 * that do not have the X11 libraries installed, which are required for the AWT subsystem to
 * operate. This method uses nearest neighbor approximation, so it's quite fast. Unfortunately,
 * the result is nowhere near as nice looking as the createHeadlessSmoothBufferedImage method.
 * //  ww w .j ava2  s  .co m
 * @param image  The image to convert
 * @param w The desired image width
 * @param h The desired image height
 * @return The converted image
 * @param type int
 */
public static BufferedImage createHeadlessBufferedImage(BufferedImage image, int type, int width, int height) {
    if (type == ImageUtils.IMAGE_PNG && hasAlpha(image)) {
        type = BufferedImage.TYPE_INT_ARGB;
    } else {
        type = BufferedImage.TYPE_INT_RGB;
    }

    BufferedImage bi = new BufferedImage(width, height, type);

    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            bi.setRGB(x, y, image.getRGB(x * image.getWidth() / width, y * image.getHeight() / height));
        }
    }

    return bi;
}

From source file:net.cloudkit.relaxation.VerifyImage.java

public static List<BufferedImage> splitImage(BufferedImage img) throws Exception {
    final List<BufferedImage> subImgs = new ArrayList<BufferedImage>();
    final int width = img.getWidth();
    final int height = img.getHeight();
    final List<Integer> weightList = new ArrayList<Integer>();
    for (int x = 0; x < width; ++x) {
        int count = 0;
        for (int y = 0; y < height; ++y) {
            if (isWhite(img.getRGB(x, y), whiteThreshold) == 0) {
                count++;//from   w  w w .  j  a  va2s . c  o m
            }
        }
        weightList.add(count);
    }
    for (int i = 0; i < weightList.size(); i++) {
        int length = 0;
        while (i < weightList.size() && weightList.get(i) > 0) {
            i++;
            length++;
        }
        if (length > 18) {
            subImgs.add(removeBlank(img.getSubimage(i - length, 0, length / 2, height), whiteThreshold, 0));
            subImgs.add(removeBlank(img.getSubimage(i - length / 2, 0, length / 2, height), whiteThreshold, 0));
        } else if (length > 5) {
            subImgs.add(removeBlank(img.getSubimage(i - length, 0, length, height), whiteThreshold, 0));
        }
    }

    return subImgs;
}

From source file:it.units.malelab.ege.util.DUMapper.java

private static void modifyMap(String fileName, float bins) throws IOException {
    Color[][] colorMap = new Color[3][];
    colorMap[0] = new Color[] { fromCode("000000"), fromCode("b36600"), fromCode("f3b300") };
    colorMap[1] = new Color[] { fromCode("376387"), fromCode("b3b3b3"), fromCode("f3e6b3") };
    colorMap[2] = new Color[] { fromCode("509dc2"), fromCode("b4d3e1"), fromCode("f3f3f3") };
    BufferedImage inImage = ImageIO.read(new File(fileName));
    BufferedImage outRGDImage = new BufferedImage(inImage.getWidth(), inImage.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
    BufferedImage outCMImage = new BufferedImage(inImage.getWidth(), inImage.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
    for (int x = 0; x < inImage.getWidth(); x++) {
        for (int y = 0; y < inImage.getHeight(); y++) {
            Color inColor = new Color(inImage.getRGB(x, y));
            Color outColor = new Color(
                    Math.min((float) Math.floor((float) inColor.getRed() / 255f * bins) / (bins - 1), 1f),
                    Math.min((float) Math.floor((float) inColor.getGreen() / 255f * bins) / (bins - 1), 1f), 0);
            outRGDImage.setRGB(x, y, outColor.getRGB());
            int cmRIndex = (int) Math.min((int) Math.floor((float) inColor.getRed() / 255f * 3), 2);
            int cmGIndex = (int) Math.min((int) Math.floor((float) inColor.getGreen() / 255f * 3), 2);
            outColor = colorMap[cmRIndex][cmGIndex];
            outCMImage.setRGB(x, y, outColor.getRGB());
        }/* w  w w .  jav a2 s.  c  o m*/
    }
    ImageIO.write(outRGDImage, "PNG",
            new File(fileName.replace(".png", String.format(".rgbdisc%d.png", (int) bins))));
    ImageIO.write(outCMImage, "PNG", new File(fileName.replace(".png", ".cm.png")));
}

From source file:com.aimluck.eip.fileupload.util.FileuploadUtils.java

/**
 * ?????????/* w w  w. j a va 2 s .c  o  m*/
 * 
 * @param imgfile
 * @param dim
 * @return
 */
public static BufferedImage shrinkImage(BufferedImage imgfile, int width, int height) {

    int iwidth = imgfile.getWidth();
    int iheight = imgfile.getHeight();

    double ratio = Math.min((double) width / (double) iwidth, (double) height / (double) iheight);
    int shrinkedWidth = (int) (iwidth * ratio);
    int shrinkedHeight = (int) (iheight * ratio);

    // ??
    Image targetImage = imgfile.getScaledInstance(shrinkedWidth, shrinkedHeight, Image.SCALE_AREA_AVERAGING);
    BufferedImage tmpImage = new BufferedImage(targetImage.getWidth(null), targetImage.getHeight(null),
            BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g = tmpImage.createGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, shrinkedWidth, shrinkedHeight);
    g.drawImage(targetImage, 0, 0, null);

    return tmpImage;
}