如何使用图像的像素绘制对象?

时间:2019-05-15 15:01:30

标签: java graphics

我有一个图像,我想在图像的像素中绘制一个可移动的矩形。 pixels [][]代表一个二维数组,其中包含所讨论图像的像素。

我该怎么做?

enter image description here

这是我到目前为止尝试过的:

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


    }
}

0 个答案:

没有答案