How to draw an object using an image's pixels?

0

I have an image and I want to draw a movable rectangle in the image's pixels. pixels [][] represents a two-dimensional array containing the pixels of the image in question.

How can I do this?

enter image description here

Here is what I have tried so far:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class NewMain extends JPanel{

    static BufferedImage image;
    static int[][] pixels;


    @Override
    public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)image.getGraphics();
            //Graphics2D g = (Graphics2D) image.getGraphics();
            //super.paintComponent(g);
            g2d.setColor(Color.red);
            g2d.fillRect(100, 300, 55, 55);
            }

    public static void main(String[] args) throws IOException {
        try {
            image = ImageIO.read(new File("f:/map5.bmp"));
        } catch (IOException ex) {
            Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
        }
        int width = image.getWidth();
        int heigh = image.getHeight();
        pixels = new int[width][heigh];
        for (int x = 0; x < width; x++) {

            for (int y = 0; y < heigh; y++) {
                pixels[x][y] = (image.getRGB(x, y) == 0xFFFFFFFF ? 1 : 0);
            }
        }
        JFrame f = new JFrame();
        JLabel label = new JLabel(new ImageIcon(image));
        f.setSize(image.getWidth(), image.getHeight());
        f.add(label);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    }
}
java
graphics
asked on Stack Overflow May 15, 2019 by zoya • edited May 17, 2019 by Mihai Chelaru

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0