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:com.aurel.track.attachment.AttachBL.java

private static BufferedImage toBufferedImage(Image image) {
    if (image instanceof BufferedImage) {
        return (BufferedImage) image;
    }//from  ww w.j av a 2s  .  co m

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

    // Determine if the image has transparent pixels; for this method's
    // implementation, see Determining If an Image Has Transparent Pixels
    boolean hasAlpha = hasAlpha(image);

    // Create a buffered image with a format that's compatible with the screen
    BufferedImage bimage = null;
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    try {
        // Determine the type of transparency of the new buffered image
        int transparency = Transparency.OPAQUE;
        if (hasAlpha) {
            transparency = Transparency.BITMASK;
        }

        // Create the buffered image
        GraphicsDevice gs = ge.getDefaultScreenDevice();
        GraphicsConfiguration gc = gs.getDefaultConfiguration();
        bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
    } catch (HeadlessException e) {
        // The system does not have a screen
    }

    if (bimage == null) {
        // Create a buffered image using the default color model
        int type = BufferedImage.TYPE_INT_RGB;
        if (hasAlpha) {
            type = BufferedImage.TYPE_INT_ARGB;
        }
        bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
    }

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

    // Paint the image onto the buffered image
    g.drawImage(image, 0, 0, null);
    g.dispose();

    return bimage;
}

From source file:com.mirth.connect.client.ui.components.MirthIconTextField.java

@Override
protected void paintComponent(Graphics g) {
    if (insets == null) {
        insets = getMargin();//from   w ww .  j a  va2 s .  c  o  m
        if (insets == null) {
            insets = new Insets(0, 0, 0, 0);
        }
    }

    if (icon != null) {
        setMargin(new Insets(insets.top, insets.left + icon.getIconWidth(), insets.bottom, insets.right));
    } else {
        setMargin(insets);
    }

    super.paintComponent(g);
    if (icon != null) {
        g.drawImage(icon.getImage(), 2, (getHeight() - icon.getIconHeight()) / 2, this);
    }
}

From source file:algorithm.QRCodeWatermarking.java

/**
 * This algorithm writes a QR-code image on a carrier image.
 * //  ww w  .  ja  v a2  s. c  o m
 * @param qrCodeFile
 * @param carrierFile
 * @param imageFormat
 * @return image file with qr code on top of carrier
 * @throws IOException
 */
private File writeQRCodeOnImage(File qrCodeFile, File carrierFile, String imageFormat) throws IOException {
    BufferedImage barcode = ImageIO.read(qrCodeFile);
    BufferedImage carrier = ImageIO.read(carrierFile);
    if (barcode.getWidth() > carrier.getWidth() || barcode.getHeight() > carrier.getHeight()) {
        displayMessage(
                "The QR-code is to big to add it to the carrier image. Try again with a lower QR-code size!");
        qrCodeFile.delete();
        return null;
    }
    Graphics graphics = carrier.getGraphics();
    graphics.drawImage(barcode, getXPosition(), getYPosition(), null);
    String outputFileName = FilenameUtils.removeExtension(getOutputFileName(carrierFile)) + "." + imageFormat;
    File outputFile = new File(outputFileName);
    ImageIO.write(carrier, imageFormat, outputFile);
    qrCodeFile.delete();
    return outputFile;
}

From source file:com.opopov.cloud.image.service.ImageStitchingServiceImpl.java

private byte[] combineImagesIntoStitchedImage(@RequestBody ImageStitchingConfiguration config,
        IndexMap indexMap) throws IOException {
    int tileWidth = config.getSourceWidth();
    int tileHeight = config.getSourceHeight();

    //we are creating this big image in memory for the very short time frame, just when
    //all source data has been downloaded and decoded
    BufferedImage image = new BufferedImage(config.getRowCount() * tileWidth,
            config.getColumnCount() * tileHeight, BufferedImage.TYPE_4BYTE_ABGR);

    Graphics g = image.getGraphics();
    int indexOfTileInList = 0;
    for (int i = 0; i < config.getRowCount(); i++) {
        for (int j = 0; j < config.getColumnCount(); j++) {
            Optional<DecodedImage> decoded = indexMap.get(indexOfTileInList++);
            if (decoded != null) {
                if (decoded.isPresent()) {
                    g.drawImage(decoded.get().getImage(), i * config.getSourceWidth(),
                            j * config.getSourceHeight(), null);
                }/*from   w  w w. j  av a 2  s .  c om*/
            }
        }
    }

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    image.flush();
    ImageIO.write(image, config.getOutputFormat(), buffer);
    g.dispose();

    return buffer.toByteArray();
}

From source file:view.ImagePanel.java

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (bi != null) {
        try {/*from  w  w  w .j av  a2  s .co m*/
            Point p = getImageLocation();
            g.drawImage(bi, p.x, p.y, this);
            g.setColor(Color.LIGHT_GRAY);
            g.drawRect(p.x, p.y, bi.getWidth(), bi.getHeight());
        } catch (Exception e) {
        }
    }
}

From source file:ColorPan.java

public void paint(Graphics g) {
    int width = getSize().width;
    int height = getSize().height;
    int[] data = new int[width * height];
    int i = 0;//from   w  ww . ja  va 2  s  .com
    for (int y = 0; y < height; y++) {
        int red = (y * 255) / (height - 1);
        for (int x = 0; x < width; x++) {
            int green = (x * 255) / (width - 1);
            int blue = 128;
            data[i++] = (red << 16) | (green << 8) | blue;
        }
    }
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    image.setRGB(0, 0, width, height, data, 0, width);
    g.drawImage(image, 0, 0, this);
}

From source file:fr.ign.cogit.simplu3d.rjmcmc.generic.visitor.FilmVisitor.java

/**
 * Permet d'enregistrer une image  partir de l'cran Ne fonctionne qu'avec
 * l'IHM actuel (Offset ncessaire) Ne prends pas compte de l'existance d'un
 * fichier de mme nom/*  ww  w.  jav a  2  s  .c  o m*/
 * 
 * @param path
 *            le dossier dans lequel l'impr ecran sera supprime
 * @param fileName
 *            le nom du fichier
 * @return indique si la capture s'est effectue avec succs
 */
public boolean screenCapture(String path, String fileName, InterfaceMap3D iMap3D) {

    try {

        ChartPanel v = StatsVisitor.CHARTSINGLETON;

        int xSup = 0;
        int ySup = 0;

        boolean hasStats = (v != null);

        if (hasStats) {

            xSup = v.getSize().width;
            ySup = v.getSize().height;

        }

        int xSize = iMap3D.getSize().width + xSup;
        int ySize = Math.max(iMap3D.getSize().height, ySup);

        BufferedImage bufImage = new BufferedImage(xSize, ySize, BufferedImage.TYPE_INT_RGB);

        Graphics g = bufImage.createGraphics();

        g.setColor(Color.white);

        // g.drawRect(0, 0, xSize, ySize);

        g.fillRect(0, 0, xSize, ySize);

        iMap3D.getCanvas3D().paint(g);

        if (hasStats) {

            g.drawImage(v.getChart().createBufferedImage(xSup, ySup), iMap3D.getSize().width,
                    (ySize - ySup) / 2, null);

        }

        File fichier = new File(path, fileName);
        if (fichier.exists()) {
            System.out.println("Fail");
            return false;
        } else {
            ImageIO.write(bufImage, "jpg", fichier);
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:ScaleTest_2008.java

/**
 * This approach uses either the getScaledInstance() approach to get
 * each new size or it scales on the fly using drawImage().
 *//*  w w w.  j  a v a  2  s  . co m*/
private void drawImage(Graphics g, int yLoc, boolean getScaled) {
    int xLoc = 100;
    int delta = (int) (SCALE_FACTOR * FULL_SIZE);
    if (getScaled) {
        for (int scaledSize = FULL_SIZE; scaledSize > 0; scaledSize -= delta) {
            Image scaledImage = originalImage.getScaledInstance(scaledSize, scaledSize,
                    Image.SCALE_AREA_AVERAGING);
            g.drawImage(scaledImage, xLoc, yLoc + (FULL_SIZE - scaledSize) / 2, null);
            xLoc += scaledSize + 20;
        }
    } else {
        for (int scaledSize = FULL_SIZE; scaledSize > 0; scaledSize -= delta) {
            g.drawImage(originalImage, xLoc, yLoc + (FULL_SIZE - scaledSize) / 2, scaledSize, scaledSize, null);
            xLoc += scaledSize + 20;
        }
    }
}

From source file:eu.delving.sip.Application.java

private Application(final File storageDir) throws StorageException {
    GroovyCodeResource groovyCodeResource = new GroovyCodeResource(getClass().getClassLoader());
    final ImageIcon backgroundIcon = new ImageIcon(getClass().getResource("/delving-background.png"));
    desktop = new JDesktopPane() {
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(backgroundIcon.getImage(), 0, 0, desktop);
        }//from w w  w  .ja va 2s.  c om
    };
    desktop.setMinimumSize(new Dimension(MINIMUM_DESKTOP_SIZE));
    resizeTimer = new Timer(DEFAULT_RESIZE_INTERVAL, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            resizeTimer.stop();
            for (JInternalFrame frame : desktop.getAllFrames()) {
                if (frame instanceof FrameBase) {
                    ((FrameBase) frame).ensureOnScreen();
                }
            }
        }
    });
    desktop.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent componentEvent) {
            resizeTimer.restart();
        }
    });
    Preferences preferences = Preferences.userNodeForPackage(SipModel.class);
    feedback = new VisualFeedback(home, desktop, preferences);
    HttpClient httpClient = createHttpClient(storageDir);
    SchemaRepository schemaRepository;
    try {
        schemaRepository = new SchemaRepository(new SchemaFetcher(httpClient));
    } catch (IOException e) {
        throw new StorageException("Unable to create Schema Repository", e);
    }
    ResolverContext context = new ResolverContext();
    Storage storage = new StorageImpl(storageDir, schemaRepository, new CachedResourceResolver(context));
    context.setStorage(storage);
    context.setHttpClient(httpClient);
    sipModel = new SipModel(desktop, storage, groovyCodeResource, feedback, preferences);
    CultureHubClient cultureHubClient = isStandalone(storageDir) ? null
            : new CultureHubClient(sipModel, httpClient);
    if (cultureHubClient != null)
        uploadAction = new UploadAction(sipModel, cultureHubClient);
    expertMenu = new ExpertMenu(desktop, sipModel, cultureHubClient, allFrames);
    statusPanel = new StatusPanel(sipModel);
    home = new JFrame(titleString());
    home.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent componentEvent) {
            allFrames.getViewSelector().refreshView();
        }
    });
    JPanel content = (JPanel) home.getContentPane();
    content.setFocusable(true);
    FrameBase dataSetFrame = cultureHubClient != null ? new DataSetHubFrame(sipModel, cultureHubClient)
            : new DataSetStandaloneFrame(sipModel, schemaRepository);
    LogFrame logFrame = new LogFrame(sipModel);
    feedback.setLog(logFrame.getLog());
    allFrames = new AllFrames(sipModel, content, dataSetFrame, logFrame);
    desktop.setBackground(new Color(190, 190, 200));
    content.add(desktop, BorderLayout.CENTER);
    sipModel.getMappingModel().addChangeListener(new MappingModel.ChangeListener() {
        @Override
        public void lockChanged(MappingModel mappingModel, final boolean locked) {
            sipModel.exec(new Swing() {
                @Override
                public void run() {
                    unlockMappingAction.setEnabled(locked);
                }
            });
        }

        @Override
        public void functionChanged(MappingModel mappingModel, MappingFunction function) {
        }

        @Override
        public void nodeMappingChanged(MappingModel mappingModel, RecDefNode node, NodeMapping nodeMapping,
                NodeMappingChange change) {
        }

        @Override
        public void nodeMappingAdded(MappingModel mappingModel, RecDefNode node, NodeMapping nodeMapping) {
        }

        @Override
        public void nodeMappingRemoved(MappingModel mappingModel, RecDefNode node, NodeMapping nodeMapping) {
        }

        @Override
        public void populationChanged(MappingModel mappingModel, RecDefNode node) {
        }
    });
    importAction = new ImportAction(desktop, sipModel);
    attachAccelerator(importAction, home);
    validateAction = new ValidateAction(sipModel, allFrames.prepareForInvestigation(desktop));
    unlockMappingAction = new UnlockMappingAction(sipModel);
    attachAccelerator(unlockMappingAction, home);
    selectAnotherMappingAction = new SelectAnotherMappingAction(sipModel);
    attachAccelerator(selectAnotherMappingAction, home);
    content.add(createStatePanel(), BorderLayout.SOUTH);
    content.add(allFrames.getSidePanel(), BorderLayout.WEST);
    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    screen.height -= 30;
    home.setSize(screen);
    home.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    ImageIcon logo = new ImageIcon(getClass().getResource("/sip-creator-logo.png"));
    home.setIconImage(logo.getImage());
    home.setJMenuBar(createMenuBar());
    home.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent windowEvent) {
            quit();
        }
    });
    home.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    sipModel.getDataSetModel().addListener(new DataSetModel.SwingListener() {
        @Override
        public void stateChanged(DataSetModel model, DataSetState state) {
            statusPanel.setState(state);
            switch (state) {
            case ABSENT:
                sipModel.exec(new Work() {
                    @Override
                    public void run() {
                        sipModel.getDataSetFacts().set(null);
                        sipModel.getStatsModel().setStatistics(null);
                    }

                    @Override
                    public Job getJob() {
                        return Job.CLEAR_FACTS_STATS;
                    }
                });
                home.setTitle(titleString());
                sipModel.seekReset();
                break;
            default:
                DataSetModel dataSetModel = sipModel.getDataSetModel();
                home.setTitle(String.format(titleString() + " - [%s -> %s]",
                        dataSetModel.getDataSet().getSpec(), dataSetModel.getPrefix().toUpperCase()));
                sipModel.getReportFileModel().refresh();
                break;
            }
        }
    });
    attachAccelerator(new QuitAction(), home);
    attachAccelerator(statusPanel.getButtonAction(), home);
}

From source file:ImagePrint.java

public int print(Graphics g, PageFormat pf, int pageIndex) {
    Graphics2D g2d = (Graphics2D) g;
    g.translate((int) (pf.getImageableX()), (int) (pf.getImageableY()));
    if (pageIndex == 0) {
        double pageWidth = pf.getImageableWidth();
        double pageHeight = pf.getImageableHeight();
        double imageWidth = printImage.getIconWidth();
        double imageHeight = printImage.getIconHeight();
        double scaleX = pageWidth / imageWidth;
        double scaleY = pageHeight / imageHeight;
        double scaleFactor = Math.min(scaleX, scaleY);
        g2d.scale(scaleFactor, scaleFactor);
        g.drawImage(printImage.getImage(), 0, 0, null);
        return Printable.PAGE_EXISTS;
    }// w  w  w  .j ava  2s  .c  o  m
    return Printable.NO_SUCH_PAGE;
}