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.zacwolf.commons.email.Email.java

/**
* This method crops an original image to the crop parameters provided.
*
* If the crop rectangle lies outside the rectangle (even if partially),
* adjusts the rectangle to be included within the image area.
*
* @param img = Original Image To Be Cropped
* @param size = Crop area rectangle/*from  www  .ja  va  2s. c  o m*/
* @param clipX = Starting X-position of crop area rectangle
* @param clipY = Strating Y-position of crop area rectangle
* @throws Exception
*/
public static Rectangle createClip(BufferedImage img, Dimension size, int clipX, int clipY) throws Exception {
    Rectangle clip;
    if ((size.width + clipX) <= img.getWidth() && (size.height + clipY) <= img.getHeight()) {
        clip = new Rectangle(size);
        clip.x = clipX;
        clip.y = clipY;
    } else {
        if ((size.width + clipX) > img.getWidth())
            size.width = img.getWidth() - clipX;
        if ((size.height + clipY) > img.getHeight())
            size.height = img.getHeight() - clipY;
        clip = new Rectangle(size);
        clip.x = clipX;
        clip.y = clipY;
    }
    return clip;
}

From source file:cn.z.Ocr5.java

public static List<BufferedImage> splitImage(BufferedImage img, String filename) 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 (CommonUtil.isWhite(img.getRGB(x, y), whiteThreshold) == 0) {
                count++;//from   www. j ava  2  s  .  com
            }
        }
        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(CommonUtil.removeBlank(img.getSubimage(i - length, 0, length / 2, height),
                    whiteThreshold, 0));
            subImgs.add(CommonUtil.removeBlank(img.getSubimage(i - length / 2, 0, length / 2, height),
                    whiteThreshold, 0));
        } else if (length > 5) {
            subImgs.add(
                    CommonUtil.removeBlank(img.getSubimage(i - length, 0, length, height), whiteThreshold, 0));
        }
    }

    //        for(int i = 0; i < subImgs.size(); i++) {
    //            FileOutputStream fos = new FileOutputStream("D:\\test\\img" + filename + i + ".jpg");
    //            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
    //            encoder.encode(subImgs.get(i));
    //            fos.close();
    //        }
    return subImgs;
}

From source file:oct.util.Util.java

/**
 * Convert the supplied image to a 2D pixel array such that an (X,Y) value
 * indexes as array[x][y].// w  ww.  j  a v  a 2s.c  om
 *
 * Credit for this method goes to Stack Overflow user Mota and their post
 * here:
 * http://stackoverflow.com/questions/6524196/java-get-pixel-array-from-image
 * for this implementation.
 *
 * This method will return the red, green and blue values directly for each
 * pixel, and if there is an alpha channel it will add the alpha value.
 * Using this method is harder in terms of calculating indices, but is much
 * faster than using getRGB to build this same array.
 *
 * @param image
 * @return
 */
public static int[][] convertTo2D(BufferedImage image) {

    final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    final int width = image.getWidth();
    final int height = image.getHeight();
    final boolean hasAlphaChannel = image.getAlphaRaster() != null;

    int[][] result = new int[width][height];
    if (hasAlphaChannel) {
        final int pixelLength = 4;
        for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
            int argb = 0;
            argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
            argb += ((int) pixels[pixel + 1] & 0xff); // blue
            argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
            argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
            result[col][row] = argb;
            col++;
            if (col == width) {
                col = 0;
                row++;
            }
        }
    } else {
        final int pixelLength = 3;
        for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
            int argb = 0;
            argb += -16777216; // 255 alpha
            argb += ((int) pixels[pixel] & 0xff); // blue
            argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
            argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
            result[col][row] = argb;
            col++;
            if (col == width) {
                col = 0;
                row++;
            }
        }
    }

    return result;
}

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

public static void updateImage(JLabel imageContainer, File imageFile) {
    if (!imageFile.exists()) {
        return;// ww  w. j a v  a  2s. c  om
    }
    BufferedImage img = null;
    try {
        img = ImageIO.read(imageFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (img == null) {
        return;
    }
    int imageWidth = img.getWidth();
    int imageHeight = img.getHeight();
    int imageViewWidth = imageContainer.getWidth();
    int imageViewHeight = imageContainer.getHeight();
    double factor = getScaleFactorToFit(new Dimension(imageWidth, imageHeight),
            new Dimension(imageViewWidth, imageViewHeight));
    factor = Math.min(factor, 1f);
    imageWidth = (int) (factor * imageWidth);
    imageHeight = (int) (factor * imageHeight);
    if (imageWidth <= 0 || imageHeight <= 0 || imageViewWidth <= 0 || imageViewHeight <= 0) {
        return;
    }
    BufferedImage tmp = UIUtil.createImage(imageViewWidth, imageViewHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = tmp.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    int x = (imageViewWidth - imageWidth) / 2;
    int y = (imageViewHeight - imageHeight) / 2;
    g2.drawImage(img, x, y, imageWidth, imageHeight, null);
    g2.dispose();
    imageContainer.setIcon(new ImageIcon(tmp));
}

From source file:iqq.util.ImageUtil.java

/**
 * ?/*from   w ww. j a v a  2 s .c  o  m*/
 *
 * @param srcFile ?
 * @param destFile 
 * @param watermarkFile ?
 * @param watermarkPosition ??
 * @param alpha ??
 */
public synchronized static void addWatermark(File srcFile, File destFile, InputStream watermarkFile,
        WatermarkPosition watermarkPosition, int alpha) {
    //watermarkFile == null || !watermarkFile.exists() || 
    if (!srcFile.exists() || watermarkFile == null || watermarkPosition == null
            || watermarkPosition == WatermarkPosition.no) {
        Log.println("addWatermark null");
        return;
    }
    if (type == Type.jdk) {
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            if (srcBufferedImage == null) {
                return;
            }
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, srcWidth, srcHeight);
            graphics2D.drawImage(srcBufferedImage, 0, 0, null);
            graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100.0F));

            BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
            int watermarkImageWidth = watermarkBufferedImage.getWidth();
            int watermarkImageHeight = watermarkBufferedImage.getHeight();
            int x = srcWidth - watermarkImageWidth;
            int y = srcHeight - watermarkImageHeight;
            if (watermarkPosition == WatermarkPosition.topLeft) {
                x = 0;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.topRight) {
                x = srcWidth - watermarkImageWidth;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.center) {
                x = (srcWidth - watermarkImageWidth) / 2;
                y = (srcHeight - watermarkImageHeight) / 2;
            } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                x = 0;
                y = srcHeight - watermarkImageHeight;
            } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                x = srcWidth - watermarkImageWidth;
                y = srcHeight - watermarkImageHeight;
            }
            graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);
            graphics2D.dispose();

            FileOutputStream out = new FileOutputStream(destFile);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(destBufferedImage);
            param.setQuality((float) DEST_QUALITY / 100, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(destBufferedImage);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        String gravity = "SouthEast";
        if (watermarkPosition == WatermarkPosition.topLeft) {
            gravity = "NorthWest";
        } else if (watermarkPosition == WatermarkPosition.topRight) {
            gravity = "NorthEast";
        } else if (watermarkPosition == WatermarkPosition.center) {
            gravity = "Center";
        } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
            gravity = "SouthWest";
        } else if (watermarkPosition == WatermarkPosition.bottomRight) {
            gravity = "SouthEast";
        }
        IMOperation operation = new IMOperation();
        operation.gravity(gravity);
        operation.dissolve(alpha);
        operation.quality((double) DEST_QUALITY);
        //operation.addImage(watermarkFile);
        operation.addImage(srcFile.getPath());
        operation.addImage(destFile.getPath());
        if (type == Type.graphicsMagick) {
            CompositeCmd compositeCmd = new CompositeCmd(true);
            if (graphicsMagickPath != null) {
                compositeCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        } else {
            CompositeCmd compositeCmd = new CompositeCmd(false);
            if (imageMagickPath != null) {
                compositeCmd.setSearchPath(imageMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.jamwiki.utils.ImageUtil.java

/**
 * Given a virtualWiki and WikiFIle that correspond to an existing image,
 * return the WikiImage object.  In addition, an optional maxDimension
 * parameter may be specified, in which case a resized version of the image
 * may be created./*from  ww w .  j av  a  2s  .c o  m*/
 *
 * @param wikiFile Given a WikiFile object, use it to initialize a
 *  WikiImage object.
 * @param maxDimension The maximum width or height for the initialized
 *  WikiImage object.  Setting this value to 0 or less will cause the
 *  value to be ignored.
 * @return An initialized WikiImage object.
 * @throws Exception Thrown if an error occurs while initializing the
 *  WikiImage object.
 */
public static WikiImage initializeImage(WikiFile wikiFile, int maxDimension) throws Exception {
    Assert.notNull(wikiFile, "wikiFile may not be null");
    WikiImage wikiImage = new WikiImage(wikiFile);
    BufferedImage imageObject = null;
    if (maxDimension > 0) {
        imageObject = ImageUtil.resizeImage(wikiImage, maxDimension);
        setScaledDimensions(imageObject, wikiImage, maxDimension);
    } else {
        File imageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH),
                wikiImage.getUrl());
        imageObject = ImageUtil.loadImage(imageFile);
        wikiImage.setWidth(imageObject.getWidth());
        wikiImage.setHeight(imageObject.getHeight());
    }
    return wikiImage;
}

From source file:com.galenframework.utils.GalenUtils.java

/**
 * Check the devicePixelRatio and adapts the size of the screenshot as if the ratio was 1.0
 * @param driver/*from  w  ww  .  ja  va2s. c om*/
 * @param screenshotImage
 * @return
 */
public static BufferedImage resizeScreenshotIfNeeded(WebDriver driver, BufferedImage screenshotImage) {
    Double devicePixelRatio = ((Number) ((JavascriptExecutor) driver)
            .executeScript(JS_RETRIEVE_DEVICE_PIXEL_RATIO)).doubleValue();

    if (devicePixelRatio > 1.0 && screenshotImage.getWidth() > 0) {
        Long screenSize = (Long) ((JavascriptExecutor) driver).executeScript(
                "return Math.max(" + "document.body.scrollWidth, document.documentElement.scrollWidth,"
                        + "document.body.offsetWidth, document.documentElement.offsetWidth,"
                        + "document.body.clientWidth, document.documentElement.clientWidth);");

        Double estimatedPixelRatio = ((double) screenshotImage.getWidth()) / ((double) screenSize);

        if (estimatedPixelRatio > 1.0) {

            int newWidth = (int) (screenshotImage.getWidth() / estimatedPixelRatio);
            int newHeight = (int) (screenshotImage.getHeight() / estimatedPixelRatio);

            Image tmp = screenshotImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
            BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

            Graphics2D g2d = scaledImage.createGraphics();
            g2d.drawImage(tmp, 0, 0, null);
            g2d.dispose();

            return scaledImage;
        } else
            return screenshotImage;
    } else
        return screenshotImage;
}

From source file:edu.ku.brc.ui.GraphicsUtils.java

/**
 * @param bufImg//from www . j  av  a2 s. co  m
 * @param size
 * @return
 */
public static BufferedImage generateScaledImage(final BufferedImage bufImg,
        @SuppressWarnings("unused") final Object hintsArg, final int size) {
    BufferedImage sourceImage = bufImg;
    int srcWidth = sourceImage.getWidth();
    int srcHeight = sourceImage.getHeight();

    double longSideForSource = Math.max(srcWidth, srcHeight);
    double longSideForDest = size;

    double multiplier = longSideForDest / longSideForSource;
    int destWidth = (int) (srcWidth * multiplier);
    int destHeight = (int) (srcHeight * multiplier);

    BufferedImage destImage = null;

    destImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = destImage.createGraphics();
    graphics2D.drawImage(sourceImage, 0, 0, destWidth, destHeight, null);
    graphics2D.dispose();

    return destImage;
}

From source file:com.googlecode.fightinglayoutbugs.helpers.ImageHelper.java

public static int[][] imageToPixels(BufferedImage image) {
    if (image == null) {
        return null;
    }//from   w w w.  j a v  a2 s. c o m
    int w = image.getWidth();
    int h = image.getHeight();
    int[][] pixels = new int[w][h];
    Raster raster = image.getRaster();
    if (raster.getTransferType() == DataBuffer.TYPE_BYTE) {
        byte[] bytes = (byte[]) raster.getDataElements(0, 0, w, h, null);
        int bytesPerPixel = (bytes.length / (w * h));
        ColorModel colorModel = image.getColorModel();
        byte[] buf = new byte[bytesPerPixel];
        for (int x = 0; x < w; ++x) {
            for (int y = 0; y < h; ++y) {
                System.arraycopy(bytes, (x + y * w) * bytesPerPixel, buf, 0, bytesPerPixel);
                pixels[x][y] = colorModel.getRGB(buf) & 0xFFFFFF;
            }
        }
        return pixels;
    } else {
        throw new RuntimeException("transfer type " + raster.getTransferType() + " not implemented yet");
    }
}

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

private static BufferedImage generateBordersImage(BufferedImage source, int trimmedWidth, int trimmedHeight)
        throws Wrong9PatchException, IOException {
    BufferedImage finalBorder = UIUtil.createImage(trimmedWidth + 2, trimmedHeight + 2,
            BufferedImage.TYPE_INT_ARGB);
    int cutW = source.getWidth() - 2;
    int cutH = source.getHeight() - 2;

    // left border
    BufferedImage leftBorder = UIUtil.createImage(1, cutH, BufferedImage.TYPE_INT_ARGB);
    leftBorder.setRGB(0, 0, 1, cutH, source.getRGB(0, 1, 1, cutH, null, 0, 1), 0, 1);
    verifyBorderImage(leftBorder);/*from w  w  w  . j av a  2s  .c  o m*/
    leftBorder = resizeBorder(leftBorder, 1, trimmedHeight);
    finalBorder.setRGB(0, 1, 1, trimmedHeight, leftBorder.getRGB(0, 0, 1, trimmedHeight, null, 0, 1), 0, 1);

    // right border
    BufferedImage rightBorder = UIUtil.createImage(1, cutH, BufferedImage.TYPE_INT_ARGB);
    rightBorder.setRGB(0, 0, 1, cutH, source.getRGB(cutW + 1, 1, 1, cutH, null, 0, 1), 0, 1);
    verifyBorderImage(rightBorder);
    rightBorder = resizeBorder(rightBorder, 1, trimmedHeight);
    finalBorder.setRGB(trimmedWidth + 1, 1, 1, trimmedHeight,
            rightBorder.getRGB(0, 0, 1, trimmedHeight, null, 0, 1), 0, 1);

    // top border
    BufferedImage topBorder = UIUtil.createImage(cutW, 1, BufferedImage.TYPE_INT_ARGB);
    topBorder.setRGB(0, 0, cutW, 1, source.getRGB(1, 0, cutW, 1, null, 0, cutW), 0, cutW);
    verifyBorderImage(topBorder);
    topBorder = resizeBorder(topBorder, trimmedWidth, 1);
    finalBorder.setRGB(1, 0, trimmedWidth, 1, topBorder.getRGB(0, 0, trimmedWidth, 1, null, 0, trimmedWidth), 0,
            trimmedWidth);

    // bottom border
    BufferedImage bottomBorder = UIUtil.createImage(cutW, 1, BufferedImage.TYPE_INT_ARGB);
    bottomBorder.setRGB(0, 0, cutW, 1, source.getRGB(1, cutH + 1, cutW, 1, null, 0, cutW), 0, cutW);
    verifyBorderImage(bottomBorder);
    bottomBorder = resizeBorder(bottomBorder, trimmedWidth, 1);
    finalBorder.setRGB(1, trimmedHeight + 1, trimmedWidth, 1,
            bottomBorder.getRGB(0, 0, trimmedWidth, 1, null, 0, trimmedWidth), 0, trimmedWidth);

    return finalBorder;
}