Example usage for java.awt Image getWidth

List of usage examples for java.awt Image getWidth

Introduction

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

Prototype

public abstract int getWidth(ImageObserver observer);

Source Link

Document

Determines the width of the image.

Usage

From source file:com.baobao121.baby.common.SimpleUploaderServlet.java

public static void changeDimension(InputStream bis, FileOutputStream desc, int w, int h) throws IOException {
    Image src = javax.imageio.ImageIO.read(bis); // Image
    int width = src.getWidth(null); // ?
    int height = src.getHeight(null); // ?
    if (width <= w && height <= h) {
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        tag.getGraphics().drawImage(src, 0, 0, width, height, null); // ??
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(desc);
        encoder.encode(tag);//w ww . j  a  v a  2 s .co m
        desc.flush();
        desc.close();
        bis.close();
    } else {
        if (width != height) {
            if (w * height < h * width) {
                h = (int) (height * w / width);
            } else {
                w = (int) (width * h / height);
            }
        }
        BufferedImage tag = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        tag.getGraphics().drawImage(src, 0, 0, w, h, null); // ??
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(desc);
        encoder.encode(tag);
        desc.flush();
        desc.close();
        bis.close();
    } // JPEG?
}

From source file:de.laures.cewolf.util.ImageHelper.java

public static BufferedImage loadBufferedImage(String fileName) {
    Image image = loadImage(fileName);
    if (image instanceof BufferedImage) {
        return (BufferedImage) image;
    }/*from   www.  j a  v  a2  s  .c o  m*/
    /*        final boolean hasAlpha = hasAlpha(image);
    int transparency = Transparency.OPAQUE;
    if (hasAlpha) {
    transparency = Transparency.BITMASK;
    }*/
    int width = (int) Math.max(1.0, image.getWidth(null));
    int height = (int) Math.max(1.0, image.getHeight(null));
    // BufferedImage bimage = GRAPHICS_CONV.createCompatibleImage(width, height, transparency);
    BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    final Graphics g = bimage.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    return bimage;
}

From source file:net.sf.webphotos.tools.Thumbnail.java

private static Image estampar(Image im) {
    try {/*from   w  w  w.  j  av  a 2 s  .  c om*/
        Image temp = new ImageIcon(im).getImage();

        BufferedImage buf = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
                BufferedImage.TYPE_INT_RGB);

        Graphics2D g2 = (Graphics2D) buf.getGraphics();

        g2.drawImage(temp, 0, 0, null);
        g2.setBackground(Color.BLUE);

        Dimension dimensaoFoto = new Dimension(im.getWidth(null), im.getHeight(null));

        // aplicar texto
        if (texto != null) {
            Util.out.println("aplicando texto " + texto);

            Font fonte = new Font(txFamilia, txEstilo, txTamanho);
            g2.setFont(fonte);
            FontMetrics fm = g2.getFontMetrics(fonte);
            Dimension dimensaoTexto = new Dimension(fm.stringWidth(texto), fm.getHeight());
            Point posTexto = calculaPosicao(dimensaoFoto, dimensaoTexto, txMargem, txPosicao);

            g2.setPaint(txCorFundo);
            g2.drawString(texto, (int) posTexto.getX() + 1, (int) posTexto.getY() + 1 + fm.getHeight());
            g2.setPaint(txCorFrente);
            g2.drawString(texto, (int) posTexto.getX(), (int) posTexto.getY() + fm.getHeight());
        }

        // aplicar marca dagua
        if (marcadagua != null) {
            Image marca = new ImageIcon(marcadagua).getImage();
            int rule = AlphaComposite.SRC_OVER;
            float alpha = (float) mdTransparencia / 100;
            Point pos = calculaPosicao(dimensaoFoto, new Dimension(marca.getWidth(null), marca.getHeight(null)),
                    mdMargem, mdPosicao);

            g2.setComposite(AlphaComposite.getInstance(rule, alpha));
            g2.drawImage(marca, (int) pos.getX(), (int) pos.getY(), null);
        }

        g2.dispose();
        //return (Image) buf;
        return Toolkit.getDefaultToolkit().createImage(buf.getSource());
    } catch (Exception e) {
        Util.err.println("[Thumbnail.estampar]/ERRO: Inesperado - " + e.getMessage());
        e.printStackTrace(Util.err);
        return im;
    }
}

From source file:org.tolven.security.bean.DocProtectionBean.java

/**
 * Create a JPEG thumbnail of the underlying image and encode it to the output stream provided.
 * The aspect ratio of the underlying image is retained. As a result, the thumbnail is scaled to fit in
 * the specified rectangle. Whitespace is added if the image does not match the aspect ratio of the rectangle. 
 * @param targetWidth//from w ww .j a  v a  2 s .c om
 * @param targetHeight
 * @param stream
 */
static public void streamJPEGThumbnail(byte[] unencryptedContent, int targetWidth, int targetHeight,
        OutputStream stream) {
    Image sourceImage = new ImageIcon(Toolkit.getDefaultToolkit().createImage(unencryptedContent)).getImage();
    float hscale = ((float) targetWidth) / ((float) sourceImage.getWidth(null));
    float vscale = ((float) targetHeight) / ((float) sourceImage.getHeight(null));
    float scale = 1.0f;
    if (hscale < scale)
        scale = hscale;
    if (vscale < scale)
        scale = vscale;
    int newWidth = (int) (sourceImage.getWidth(null) * scale);
    int newHeight = (int) (sourceImage.getHeight(null) * scale);
    Image resizedImage = scaleImage(sourceImage, newWidth, newHeight);
    BufferedImage bufferedImage = toBufferedImage(resizedImage, targetWidth, targetHeight);

    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(stream);
    try {
        encoder.encode(bufferedImage);
    } catch (Exception ex) {
        throw new RuntimeException("Could not encode bufferedImage", ex);
    }
}

From source file:rega.genotype.ui.util.GenotypeLib.java

public static void scalePNG(File in, File out, double perc) throws IOException {
    Image i = ImageIO.read(in);
    Image resizedImage = null;/* w  ww  . jav  a 2  s.c o  m*/

    int newWidth = (int) (i.getWidth(null) * perc / 100.0);
    int newHeight = (int) (i.getHeight(null) * perc / 100.0);

    resizedImage = i.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);

    // This code ensures that all the pixels in the image are loaded.
    Image temp = new ImageIcon(resizedImage).getImage();

    // Create the buffered image.
    BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
            BufferedImage.TYPE_INT_RGB);

    // Copy image to buffered image.
    Graphics g = bufferedImage.createGraphics();

    // Clear background and paint the image.
    g.setColor(Color.white);
    g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
    g.drawImage(temp, 0, 0, null);
    g.dispose();

    // Soften.
    float softenFactor = 0.05f;
    float[] softenArray = { 0, softenFactor, 0, softenFactor, 1 - (softenFactor * 4), softenFactor, 0,
            softenFactor, 0 };
    Kernel kernel = new Kernel(3, 3, softenArray);
    ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
    bufferedImage = cOp.filter(bufferedImage, null);

    ImageIO.write(bufferedImage, "png", out);
}

From source file:org.jfree.experimental.swt.SWTUtils.java

/**
 * Converts an AWT image to SWT.//  ww  w  . j  a  v a 2  s. c  o  m
 *
 * @param image  the image (<code>null</code> not permitted).
 *
 * @return Image data.
 */
public static ImageData convertAWTImageToSWT(Image image) {
    ParamChecks.nullNotPermitted(image, "image");
    int w = image.getWidth(null);
    int h = image.getHeight(null);
    if (w == -1 || h == -1) {
        return null;
    }
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.getGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    return convertToSWT(bi);
}

From source file:net.sf.webphotos.tools.Thumbnail.java

private static boolean save(Image thumbnail, String nmArquivo) {
    try {//w ww.  j ava2s .  c  o m
        // This code ensures that all the
        // pixels in the image are loaded.
        Image temp = new ImageIcon(thumbnail).getImage();

        // Create the buffered image.
        BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
                BufferedImage.TYPE_INT_RGB);

        // Copy image to buffered image.
        Graphics g = bufferedImage.createGraphics();

        // Clear background and paint the image.
        g.setColor(Color.white);
        g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
        g.drawImage(temp, 0, 0, null);
        g.dispose();

        // write the jpeg to a file
        File file = new File(nmArquivo);
        // Recria o arquivo se existir
        if (file.exists()) {
            Util.out.println("Redefinindo a Imagem: " + nmArquivo);
            file.delete();
            file = new File(nmArquivo);
        }

        // encodes image as a JPEG file
        ImageIO.write(bufferedImage, IMAGE_FORMAT, file);

        return true;
    } catch (IOException ioex) {
        ioex.printStackTrace(Util.err);
        return false;
    }
}

From source file:org.sbs.util.ImageCompress.java

/** Checks the given image for valid width and height. */
private static void checkImage(Image image) {
    waitForImage(image);//w ww .  j  a  va 2s  .c  o m
    int imageWidth = image.getWidth(null);
    if (imageWidth < 1)
        throw new IllegalArgumentException("image width " + imageWidth + " is out of range");
    int imageHeight = image.getHeight(null);
    if (imageHeight < 1)
        throw new IllegalArgumentException("image height " + imageHeight + " is out of range");
}

From source file:org.pentaho.reporting.engine.classic.core.layout.output.RenderUtility.java

public static Image scaleImage(final Image img, final int targetWidth, final int targetHeight,
        final Object hintValue, final boolean higherQuality) {
    final int type = BufferedImage.TYPE_INT_ARGB;

    Image ret = img;
    int w;/*from w  w w. ja  v a2s . c o m*/
    int h;
    do {

        if (higherQuality) {
            final int imageWidth = ret.getWidth(null);
            final int imageHeight = ret.getHeight(null);
            if (imageWidth < targetWidth) {
                // This is a up-scale operation.
                w = Math.min(imageWidth << 1, targetWidth);
            } else if (imageWidth > targetWidth) {
                // downscale
                w = Math.max(imageWidth >> 1, targetWidth);
            } else {
                w = imageWidth;
            }

            if (imageHeight < targetHeight) {
                // This is a up-scale operation.
                h = Math.min(imageHeight << 1, targetHeight);
            } else if (imageHeight > targetHeight) {
                // downscale
                h = Math.max(imageHeight >> 1, targetHeight);
            } else {
                h = imageHeight;
            }
        } else {
            w = targetWidth;
            h = targetHeight;
        }

        final BufferedImage tmp = new BufferedImage(w, h, type);
        final Graphics2D g2 = tmp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hintValue);
        // this one scales the image ..
        if (ret instanceof BufferedImage) {
            if (g2.drawImage(ret, 0, 0, w, h, null) == false) {
                logger.debug("Failed to scale the image. This should not happen.");
            }
        } else {
            final WaitingImageObserver obs = new WaitingImageObserver(ret);
            while (g2.drawImage(ret, 0, 0, w, h, null) == false) {
                obs.waitImageLoaded();
                if (obs.isError()) {
                    logger.warn("Error while loading the image during the rendering.");
                    break;
                }
            }

        }
        g2.dispose();

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

    return ret;
}

From source file:net.sf.webphotos.tools.Thumbnail.java

/**
 * Cria thumbs para as imagens. Testa se j existem valores setados para o
 * thumb, se no existir chama o mtodo/*from   w w w  .  ja  v  a  2  s .  co m*/
 * {@link net.sf.webphotos.Thumbnail#inicializar() inicializar} para setar
 * seus valores. Abre o arquivo de imagem passado como parmetro e checa se
 *  uma foto vlida. Obtm o tamanho original da imagem, checa se est no
 * formato paisagem ou retrato e utiliza o mtodo
 * {@link java.awt.Image#getScaledInstance(int,int,int) getScaledInstance}
 * para calcular os thumbs. Ao final, salva as imagens.
 *
 * @param caminhoCompletoImagem Caminho da imagem.
 */
public static void makeThumbs(String caminhoCompletoImagem) {

    String diretorio, arquivo;
    if (t1 == 0) {
        inicializar();
    }

    try {
        File f = new File(caminhoCompletoImagem);
        if (!f.isFile() || !f.canRead()) {
            Util.err.println("[Thumbnail.makeThumbs]/ERRO: Erro no caminho do arquivo " + caminhoCompletoImagem
                    + " incorreto");
            return;
        }

        // Foto em alta corrompida 
        if (getFormatName(f) == null) {
            Util.err.println("[Thumbnail.makeThumbs]/ERRO: Foto Corrompida");
            return;
        } else {
            Util.out.println("[Thumbnail.makeThumbs]/INFO: Foto Ok!");
        }

        diretorio = f.getParent();
        arquivo = f.getName();

        ImageIcon ii = new ImageIcon(f.getCanonicalPath());
        Image i = ii.getImage();

        Image tumb1, tumb2, tumb3, tumb4;

        // obtm o tamanho da imagem original
        int iWidth = i.getWidth(null);
        int iHeight = i.getHeight(null);
        //int w, h;

        if (iWidth > iHeight) {
            tumb1 = i.getScaledInstance(t1, (t1 * iHeight) / iWidth, Image.SCALE_SMOOTH);
            tumb2 = i.getScaledInstance(t2, (t2 * iHeight) / iWidth, Image.SCALE_SMOOTH);
            tumb3 = i.getScaledInstance(t3, (t3 * iHeight) / iWidth, Image.SCALE_SMOOTH);
            tumb4 = i.getScaledInstance(t4, (t4 * iHeight) / iWidth, Image.SCALE_SMOOTH);
            //w = t4;
            //h = (t4 * iHeight) / iWidth;
        } else {
            tumb1 = i.getScaledInstance((t1 * iWidth) / iHeight, t1, Image.SCALE_SMOOTH);
            tumb2 = i.getScaledInstance((t2 * iWidth) / iHeight, t2, Image.SCALE_SMOOTH);
            tumb3 = i.getScaledInstance((t3 * iWidth) / iHeight, t3, Image.SCALE_SMOOTH);
            tumb4 = i.getScaledInstance((t4 * iWidth) / iHeight, t4, Image.SCALE_SMOOTH);
            //w = (t4 * iWidth) / iHeight;
            //h = t4;
        }

        tumb4 = estampar(tumb4);

        Util.log("Salvando Imagens");

        save(tumb1, diretorio + File.separator + "_a" + arquivo);
        save(tumb2, diretorio + File.separator + "_b" + arquivo);
        save(tumb3, diretorio + File.separator + "_c" + arquivo);
        save(tumb4, diretorio + File.separator + "_d" + arquivo);

    } catch (Exception e) {
        Util.err.println("[Thumbnail.makeThumbs]/ERRO: Inesperado - " + e.getMessage());
        e.printStackTrace(Util.err);
    }
}