Example usage for java.awt Graphics drawImage

List of usage examples for java.awt Graphics drawImage

Introduction

In this page you can find the example usage for java.awt Graphics drawImage.

Prototype

public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer);

Source Link

Document

Draws as much of the specified image as is currently available.

Usage

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

private static boolean save(Image thumbnail, String nmArquivo) {
    try {/*  w w w  .ja  v  a 2s  .co 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.osmdroid.geopackagetoosm.Main.java

/**
 * Write GeoPackage formatted tiles/*from   w w  w  .j ava  2  s .c  o  m*/
 *
 * @param tileDao
 * @param zoomLevel
 * @param tileMatrix
 * @param zDirectory
 * @param imageFormat
 * @param rawImage
 * @return
 * @throws IOException
 */
private static int writeGeoPackageFormatTiles(TileDao tileDao, long zoomLevel, TileMatrix tileMatrix,
        File zDirectory, String imageFormat, boolean rawImage) throws IOException {

    int tileCount = 0;

    // Go through each x in the width
    for (int x = 0; x < tileMatrix.getMatrixWidth(); x++) {

        File xDirectory = new File(zDirectory, String.valueOf(x));

        // Go through each y in the height
        for (int y = 0; y < tileMatrix.getMatrixHeight(); y++) {

            // Query for a tile at the x, y, z
            TileRow tileRow = tileDao.queryForTile(x, y, zoomLevel);

            if (tileRow != null) {

                // Get the image bytes
                byte[] tileData = tileRow.getTileData();

                if (tileData != null) {

                    // Make any needed directories for the image
                    xDirectory.mkdirs();

                    File imageFile = new File(xDirectory, String.valueOf(y) + "." + imageFormat);

                    if (rawImage) {

                        // Write the raw image bytes to the file
                        FileOutputStream fos = new FileOutputStream(imageFile);
                        fos.write(tileData);
                        fos.close();

                    } else {

                        // Read the tile image
                        BufferedImage tileImage = tileRow.getTileDataImage();

                        // Create the new image in the image format
                        BufferedImage image = ImageUtils.createBufferedImage(tileImage.getWidth(),
                                tileImage.getHeight(), imageFormat);
                        Graphics graphics = image.getGraphics();

                        // Draw the image
                        graphics.drawImage(tileImage, 0, 0, null);

                        // Write the image to the file
                        ImageIO.write(image, imageFormat, imageFile);
                    }

                    tileCount++;

                    if (tileCount % ZOOM_PROGRESS_FREQUENCY == 0) {
                        LOGGER.log(Level.INFO, "Zoom " + zoomLevel + " Tile Progress... " + tileCount);
                    }
                }
            }
        }
    }

    return tileCount;
}

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  w  w . j a v  a2 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.tolven.security.bean.DocProtectionBean.java

/**
 * Place the resulting scaled image into the output buffer
 * @param image The scaled image/*from ww  w  .  java 2 s  .c  o m*/
 * @param windowWidth The desired window width to return
 * @param windowHeight The desired window hight to return
 * @return A Buffered image, ready for output
 */
static public BufferedImage toBufferedImage(Image image, int windowWidth, int windowHeight) {
    image = new ImageIcon(image).getImage();
    BufferedImage bufferedImage = new BufferedImage(windowWidth, windowHeight, BufferedImage.TYPE_INT_RGB);
    Graphics g = bufferedImage.createGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, windowWidth, windowHeight);
    // Center image in window
    int hOffset = (windowWidth - image.getWidth(null)) / 2;
    int vOffset = (windowHeight - image.getHeight(null)) / 2;
    g.drawImage(image, hOffset, vOffset, null);
    g.dispose();
    return bufferedImage;
}

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

/**
 * Creates a Black and White image from the color
 * @param img the image to be converted//w  ww  .  j  a v a 2s . c om
 * @return new B&W image
 */
public static ImageIcon createBWImage(final ImageIcon img) {
    BufferedImage bi = new BufferedImage(img.getIconWidth(), img.getIconHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.createGraphics();
    g.drawImage(img.getImage(), 0, 0, null);
    ColorConvertOp colorConvert = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
    colorConvert.filter(bi, bi);
    ImageIcon icon = new ImageIcon(bi);
    g.dispose();
    return icon;
}

From source file:view.FramePrincipal.java

private static BufferedImage createBufferedImage(String fileName) {
    BufferedImage image = null;/*from  w  ww  .ja  v  a2 s  .  co m*/
    try {
        image = ImageIO.read(new File(fileName));
    } catch (IOException e) {
        return null;
    }

    int sizeX = image.getWidth();
    int sizeY = image.getHeight();

    BufferedImage result = new BufferedImage(sizeX, sizeY, BufferedImage.TYPE_INT_RGB);
    Graphics g = result.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    return result;
}

From source file:levelBuilder.DialogMaker.java

/**
 * First window to interact with. Offers options of load graph or new graph.
 *///  ww w  .  j av a 2s  .  co  m
private static void splashWindow() {
    final JFrame frame = new JFrame("Dialog Maker");

    //Handles button pushes.
    class SplashActionHandler implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            frame.dispose();
            if (e.getActionCommand().equals("loadGraph"))
                loadFilePopup();
            else
                loadGraph(true);
        }
    }

    //Loads and sets background image.
    BufferedImage img = null;
    try {
        img = ImageIO.read(new File(imgDir + "splash.png"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    final BufferedImage img2 = img;
    JPanel panel = new JPanel() {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(img2, 0, 0, null);
        }
    };

    panel.setOpaque(true);
    panel.setLayout(new BorderLayout());
    panel.setPreferredSize(new Dimension(800, 600));
    panel.setBorder(BorderFactory.createEmptyBorder(0, 0, 300, 0));

    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    buttonPanel.setOpaque(false);

    //Buttons
    JButton loadMap = new JButton("Load Graph");
    loadMap.setActionCommand("loadGraph");
    loadMap.addActionListener(new SplashActionHandler());
    buttonPanel.add(loadMap);

    JButton newMap = new JButton("New Graph");
    newMap.setActionCommand("newGraph");
    newMap.addActionListener(new SplashActionHandler());
    buttonPanel.add(newMap);

    panel.add(buttonPanel, BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
}

From source file:net.cbtltd.server.UploadFileService.java

private static byte[] getImageBlob(String fn, int fullsizepixels) {
    try {/*from w  w w .ja v a  2s. c  om*/
        ImageIcon image = new ImageIcon(fn);

        ImageIcon logoImage = new ImageIcon(
                image.getImage().getScaledInstance(fullsizepixels, -1, Image.SCALE_SMOOTH));
        BufferedImage bufferedImage = new BufferedImage(logoImage.getIconWidth(), logoImage.getIconHeight(),
                BufferedImage.TYPE_INT_RGB);
        Graphics graphics = bufferedImage.getGraphics();
        graphics.drawImage(logoImage.getImage(), 0, 0, null);
        fn = fn.substring(0, fn.lastIndexOf('.')) + ".Blob.jpg";
        File file = new File(fn);
        file.delete();
        ImageIO.write(bufferedImage, FULLSIZE_JPEG, file);

        InputStream is = new FileInputStream(file);
        long length = file.length();
        if (length > Integer.MAX_VALUE) {
            throw new IOException("File is too large for logo - maximum size = " + Integer.MAX_VALUE);
        }
        byte[] bytes = new byte[(int) length];
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }
        is.close();

        return bytes;
    } catch (IOException x) {
        throw new RuntimeException("Error creating BLOB image " + x.getMessage());
    }
}

From source file:net.cbtltd.server.UploadFileService.java

private static boolean getImage(String fn, int fullsizepixels, int thumbnailpixels) {

    ImageIcon image = new ImageIcon(fn);
    //      if(image.getIconHeight() > 0 && image.getIconWidth() > 0) {
    if (image.getImageLoadStatus() == MediaTracker.COMPLETE) {
        ImageIcon fullsizeImage = new ImageIcon(
                image.getImage().getScaledInstance(-1, fullsizepixels, Image.SCALE_SMOOTH));
        LOG.debug("\n UploadFileService setImage image= " + image + " width=" + fullsizeImage.getIconWidth()
                + "  height=" + fullsizeImage.getIconHeight());
        BufferedImage fullsizeBufferedImage = new BufferedImage(fullsizeImage.getIconWidth(),
                fullsizeImage.getIconHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics fullsizeGraphics = fullsizeBufferedImage.getGraphics();
        fullsizeGraphics.drawImage(fullsizeImage.getImage(), 0, 0, null);
        File fullsizeFile = new File(fn.substring(0, fn.lastIndexOf('.')) + ".jpg");
        fullsizeFile.delete();// w  w  w.java  2s .c  o m

        try {
            ImageIO.write(fullsizeBufferedImage, FULLSIZE_JPEG, fullsizeFile);
        } catch (IOException x) {
            throw new RuntimeException("Error saving full sized image " + x.getMessage());
        }

        ImageIcon thumbnailImage = new ImageIcon(
                image.getImage().getScaledInstance(-1, thumbnailpixels, Image.SCALE_SMOOTH));
        File thumbnailFile = new File(fn.substring(0, fn.lastIndexOf('.')) + "Thumb.jpg");
        thumbnailFile.delete();
        BufferedImage thumbnailBufferedImage = new BufferedImage(thumbnailImage.getIconWidth(),
                thumbnailImage.getIconHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics thumbnailGraphics = thumbnailBufferedImage.getGraphics();
        thumbnailGraphics.drawImage(thumbnailImage.getImage(), 0, 0, null);
        try {
            ImageIO.write(thumbnailBufferedImage, FULLSIZE_JPEG, thumbnailFile);
        } catch (IOException x) {
            throw new RuntimeException("Error saving thumbnail image " + x.getMessage());
        }
        return true;
    } else {
        LOG.error("\n UploadFileService setImage image= " + image + " width=" + image.getIconWidth()
                + "  height=" + image.getIconHeight());
        return false;
    }
}

From source file:net.cbtltd.server.UploadFileService.java

private static boolean getImage(String fn, BufferedImage image, Map<String, byte[]> images) {
    int fullsizepixels = Text.FULLSIZE_PIXELS_VALUE;
    int thumbnailpixels = Text.THUMBNAIL_PIXELS_VALUE;
    //      ByteBuffer byteArray = new ByteBuffer();
    ByteArrayOutputStream bOutputReg = new ByteArrayOutputStream();
    ByteArrayOutputStream bOutputThumb = new ByteArrayOutputStream();
    ImageIcon imageIcon = new ImageIcon(image);
    //      if(image.getIconHeight() > 0 && image.getIconWidth() > 0) {
    if (imageIcon.getImageLoadStatus() == MediaTracker.COMPLETE) {
        ImageIcon fullsizeImage = new ImageIcon(
                imageIcon.getImage().getScaledInstance(-1, fullsizepixels, Image.SCALE_SMOOTH));
        LOG.debug("\n UploadFileService setImage image= " + imageIcon + " width=" + fullsizeImage.getIconWidth()
                + "  height=" + fullsizeImage.getIconHeight());
        BufferedImage fullsizeBufferedImage = new BufferedImage(fullsizeImage.getIconWidth(),
                fullsizeImage.getIconHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics fullsizeGraphics = fullsizeBufferedImage.getGraphics();
        fullsizeGraphics.drawImage(fullsizeImage.getImage(), 0, 0, null);
        String fullsizeFile = fn.substring(0, fn.lastIndexOf('.')) + ".jpg";

        try {/*  w  w w. j  a va 2s .  c om*/
            ImageIO.write(fullsizeBufferedImage, FULLSIZE_JPEG, bOutputReg);
            bOutputReg.flush();
            images.put(fullsizeFile, bOutputReg.toByteArray());
            bOutputReg.close();
        } catch (IOException x) {
            throw new RuntimeException("Error saving full sized image " + x.getMessage());
        } catch (Exception e) {
            LOG.error(e.getMessage() + " Error saving full sized image: " + fullsizeFile);
        }

        ImageIcon thumbnailImage = new ImageIcon(
                imageIcon.getImage().getScaledInstance(-1, thumbnailpixels, Image.SCALE_SMOOTH));
        String thumbnailFile = fn.substring(0, fn.lastIndexOf('.')) + "Thumb.jpg";

        BufferedImage thumbnailBufferedImage = new BufferedImage(thumbnailImage.getIconWidth(),
                thumbnailImage.getIconHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics thumbnailGraphics = thumbnailBufferedImage.getGraphics();
        thumbnailGraphics.drawImage(thumbnailImage.getImage(), 0, 0, null);
        try {
            ImageIO.write(thumbnailBufferedImage, FULLSIZE_JPEG, bOutputThumb);
            bOutputThumb.flush();
            images.put(thumbnailFile, bOutputThumb.toByteArray());
            bOutputThumb.close();
        } catch (IOException x) {
            throw new RuntimeException("Error saving thumbnail image " + x.getMessage());
        } catch (Exception e) {
            LOG.error(e.getMessage() + " Error saving thumbnail image: " + thumbnailFile);
        }

        return true;
    } else {
        LOG.error("\n UploadFileService setImage image= " + imageIcon + " width=" + imageIcon.getIconWidth()
                + "  height=" + imageIcon.getIconHeight());
        return false;
    }
}