Example usage for java.awt.image BufferedImage getHeight

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

Introduction

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

Prototype

public int getHeight() 

Source Link

Document

Returns the height of the BufferedImage .

Usage

From source file:com.el.ecom.utils.ImageUtils.java

/**
 * ?// w w  w . j ava 2  s. c o m
 * 
 * @param srcFile ?
 * @param destFile 
 * @param watermarkFile ?
 * @param watermarkPosition ??
 * @param alpha ??
 */
public static void addWatermark(File srcFile, File destFile, File watermarkFile,
        WatermarkPosition watermarkPosition, int alpha) {
    Assert.notNull(srcFile);
    Assert.state(srcFile.exists());
    Assert.state(srcFile.isFile());
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);

    if (watermarkFile == null || !watermarkFile.exists() || !watermarkFile.isFile() || watermarkPosition == null
            || watermarkPosition == WatermarkPosition.no) {
        try {
            if (!StringUtils.equals(srcFile.getCanonicalPath(), destFile.getCanonicalPath())) {
                FileUtils.copyFile(srcFile, destFile);
            }
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return;
    }
    if (type == Type.jdk) {
        Graphics2D graphics2D = null;
        ImageOutputStream imageOutputStream = null;
        ImageWriter imageWriter = null;
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight,
                    BufferedImage.TYPE_INT_RGB);
            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 / 100F));

            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);

            imageOutputStream = ImageIO.createImageOutputStream(destFile);
            imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                    .next();
            imageWriter.setOutput(imageOutputStream);
            ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
            imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imageWriteParam.setCompressionQuality(DEST_QUALITY / 100F);
            imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
            imageOutputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (graphics2D != null) {
                graphics2D.dispose();
            }
            if (imageWriter != null) {
                imageWriter.dispose();
            }
            try {
                if (imageOutputStream != null) {
                    imageOutputStream.close();
                }
            } catch (IOException e) {
            }
        }
    } 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);
        try {
            operation.addImage(watermarkFile.getCanonicalPath());
            operation.addImage(srcFile.getCanonicalPath());
            operation.addImage(destFile.getCanonicalPath());
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        if (type == Type.graphicsMagick) {
            CompositeCmd compositeCmd = new CompositeCmd(true);
            if (graphicsMagickPath != null) {
                compositeCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (IM4JavaException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        } else {
            CompositeCmd compositeCmd = new CompositeCmd(false);
            if (imageMagickPath != null) {
                compositeCmd.setSearchPath(imageMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (IM4JavaException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}

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++;//w  w w  . ja va  2s. c  om
            }
        }
        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 w w.  j a v  a  2 s . c o m
 *
 * 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;/* w w  w . ja  v a  2s. co  m*/
    }
    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:com.aurel.track.item.PrintItemDetailsBL.java

/**
 * The big difference relative to other FlatHistoryBean of RENDER_TYPE=ACTUAL_VALUES is that 
 * some of HistoryEntries of FlatHistoryBean have oldValue set which means special handling in jsp:
 * either rendering a image or create a link for attachment
 * @param attachmentBeans/* w ww .  ja  v a  2  s  .  co  m*/
 * @param locale
 * @return
 */
private static List<FlatHistoryBean> loadAttachmentFlatHistoryBeans(List<TAttachmentBean> attachmentBeans,
        Map<Integer, TWorkItemBean> workItemBeansMap, Locale locale, boolean withChildren) {
    List<FlatHistoryBean> flatValueList = new ArrayList<FlatHistoryBean>();
    Integer stretchPercent = null;
    Integer maxWidth = null;
    Integer maxHeight = null;
    Properties properties = loadConfigFromFile();
    stretchPercent = getConfigByName(properties, "stretchPercent", 100);
    maxWidth = getConfigByName(properties, "maxWidth", 500);
    maxHeight = getConfigByName(properties, "maxHeight", 500);
    if (attachmentBeans != null) {
        for (TAttachmentBean attachmentBean : attachmentBeans) {
            FlatHistoryBean flatHistoryBean = new FlatHistoryBean();
            List<HistoryEntry> historyEntries = new ArrayList<HistoryEntry>();
            flatHistoryBean.setHistoryEntries(historyEntries);
            flatHistoryBean.setChangedByName(attachmentBean.getChangedByName());
            flatHistoryBean.setPersonID(attachmentBean.getChangedBy());
            flatHistoryBean.setLastEdit(attachmentBean.getLastEdit());
            flatHistoryBean.setType(HistoryBean.HISTORY_TYPE.ATTACHMENT);
            flatHistoryBean.setIconName("attachment.png");
            HistoryLoaderBL.addWorkItemToFlatHistoryBean(flatHistoryBean, workItemBeansMap,
                    attachmentBean.getWorkItem(), FlatHistoryBean.RENDER_TYPE.ACTUAL_VALUES);
            flatHistoryBean.setWorkItemID(attachmentBean.getWorkItem());

            HistoryEntry historyEntry = new HistoryEntry();
            /*render the attachmnet download: 
            historyEntry.fieldLabel -> Name
            historyEntry.newValue -> the fileName
            historyEntry.oldValue -> attachmentID: the value is used in the URL                   
            */
            historyEntry.setFieldLabel(
                    LocalizeUtil.getLocalizedTextFromApplicationResources("common.lbl.name", locale));
            historyEntry.setNewValue(attachmentBean.getFileName());
            historyEntry.setOldValue(attachmentBean.getObjectID().toString());

            historyEntries.add(historyEntry);
            if (!withChildren) {
                historyEntry = new HistoryEntry();
                historyEntry.setFieldLabel(
                        LocalizeUtil.getLocalizedTextFromApplicationResources("common.lbl.size", locale));
                historyEntry.setNewValue(TAttachmentBean.getFileSizeString(attachmentBean.getSize()));
                historyEntries.add(historyEntry);

                String description = attachmentBean.getDescription();
                if (description != null && !"".equals(description)) {
                    historyEntry = new HistoryEntry();
                    historyEntry.setFieldLabel(LocalizeUtil
                            .getLocalizedTextFromApplicationResources("common.lbl.description", locale));
                    historyEntry.setNewValue(description);
                    historyEntries.add(historyEntry);
                }
            }
            boolean isImage = AttachBL.isImage(attachmentBean);
            if (isImage) {
                /*render the image: 
                   historyEntry.fieldLabel -> null
                   historyEntry.newValue -> image width (in pixels)
                   historyEntry.oldValue -> attachmentID: used in the URL                
                */
                TAttachmentBean attachmentBeanPopulated = AttachBL.loadAttachment(attachmentBean.getObjectID(),
                        attachmentBean.getWorkItem(), true);
                String fileNameOnDisk = attachmentBeanPopulated.getFullFileNameOnDisk();
                File f = new File(fileNameOnDisk);
                BufferedImage image;
                Integer originalWidth = null;
                Integer originalHeight = null;
                try {
                    image = ImageIO.read(f);
                    originalWidth = image.getWidth();
                    originalHeight = image.getHeight();
                } catch (IOException e) {
                    LOGGER.warn("Reading the image failed with " + e.getMessage());
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                }

                if (fileNameOnDisk != null && !"".equals(fileNameOnDisk)) {
                    historyEntry = new HistoryEntry();
                    if (originalWidth != null && originalHeight != null) {
                        Integer calculatedWidth = Integer
                                .valueOf(originalWidth.intValue() * stretchPercent / 100);
                        Integer calculatedHeight = Integer
                                .valueOf(originalHeight.intValue() * stretchPercent / 100);
                        if (calculatedWidth.intValue() > maxWidth.intValue()
                                && calculatedHeight.intValue() > maxHeight.intValue()) {
                            double widthScale = calculatedWidth.doubleValue() / maxWidth.doubleValue();
                            double heightScale = calculatedHeight.doubleValue() / maxHeight.doubleValue();
                            if (widthScale > heightScale) {
                                calculatedWidth = maxWidth;
                            } else {
                                calculatedWidth = Integer.valueOf((int) (calculatedWidth.doubleValue()
                                        * maxHeight.doubleValue() / calculatedHeight.doubleValue()));
                            }
                        } else {
                            if (calculatedWidth.intValue() > maxWidth.intValue()) {
                                calculatedWidth = maxWidth;
                            } else {
                                if (calculatedHeight.intValue() > maxHeight.intValue()) {
                                    calculatedWidth = Integer.valueOf((int) (calculatedWidth.doubleValue()
                                            * maxHeight.doubleValue() / calculatedHeight.doubleValue()));
                                }
                            }
                        }
                        historyEntry.setNewValue(calculatedWidth.toString());
                    }
                    historyEntry.setOldValue(attachmentBean.getObjectID().toString());
                    historyEntries.add(historyEntry);
                }
            }
            flatValueList.add(flatHistoryBean);
        }
    }
    return flatValueList;
}

From source file:common.utils.ImageUtils.java

/**
  * resize input image to new dinesions(only smaller) and save it to file
  * @param image input image for scaling
  * @param scale_factor factor for scaling image
 * @param rez writes resulting image to a file
 * @throws IOException/*from w  w  w  .j a v a2  s.  c  om*/
  */
public static void saveScaledImageWidth(BufferedImage image, double scale_factor, OutputStream rez)
        throws IOException {
    //long time_resize = System.currentTimeMillis();
    if (scale_factor == 1) {
        writeImage(image, 1, rez);
    } else {
        int width = (int) (scale_factor * image.getWidth());
        int height = (int) (scale_factor * image.getHeight());
        //BufferedImage scaled_bi = new BufferedImage( image.getWidth(), image.getHeight(), image.getType() );
        int type = image.getType();
        BufferedImage scaled_bi;
        if (type == BufferedImage.TYPE_CUSTOM) {
            scaled_bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        } else {
            scaled_bi = new BufferedImage(width, height, type);
        }

        Graphics2D g2 = scaled_bi.createGraphics();

        //g2.drawImage(image, at, null);
        g2.drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        writeImage(scaled_bi, 1, rez);

        g2.dispose();
    }
    //time_resize = System.currentTimeMillis() - time_resize;
    //System.out.print("time_resize=" + (time_resize) + "; ");
}

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:net.rptools.lib.image.ImageUtil.java

public static void clearImage(BufferedImage image) {
    if (image == null)
        return;// w w  w.j a  v a2  s.co  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:com.simiacryptus.mindseye.applications.ArtistryUtil.java

/**
 * Paint lines.//from   w  w w.ja v  a 2s  .c om
 *
 * @param canvas the canvas
 */
public static void paint_Lines(final Tensor canvas) {
    BufferedImage originalImage = canvas.toImage();
    BufferedImage newImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = (Graphics2D) newImage.getGraphics();
    IntStream.range(0, 100).forEach(i -> {
        Random random = new Random();
        graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
        graphics.drawLine(random.nextInt(originalImage.getWidth()), random.nextInt(originalImage.getHeight()),
                random.nextInt(originalImage.getWidth()), random.nextInt(originalImage.getHeight()));
    });
    canvas.set(Tensor.fromRGB(newImage));
}

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

/**
 * @param bufImg//from w  w  w  .ja  v  a  2  s  .  com
 * @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;
}