Java Graphics - Count number of pixels used in fillRect function
I have given here Java Graphics program to count the number of pixels used to fill a rectangle by fillRect function.
Source Code
import java.lang.*; import java.util.*; import java.util.List; import java.io.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.Image.*; import javax.swing.JFrame; import javax.swing.JPanel; public class CountPixels_FillRect extends JPanel { static public int pixelDrawnCount = 0; static public int width = 300; static public int height = 300; public java.awt.image.BufferedImage myshape = new java.awt.image.BufferedImage(width,height, java.awt.image.BufferedImage.TYPE_INT_RGB); public int CountPixelsIn_fillRect(int x1, int y1, int x2, int y2) { Graphics2D gtemp = myshape.createGraphics(); gtemp.setPaint(Color.white); gtemp.fillRect(0,0,width,width); gtemp.setPaint(Color.blue); gtemp.fillRect(x1,y1,x2,y2); int pixelcount = 0; for(int i = 0; i < width; i++) { for(int j = 0; j < height; j++) { int color = myshape.getRGB(i,j); int red = (color & 0x00ff0000) >> 16; int green = (color & 0x0000ff00) >> 8; int blue = color & 0x000000ff; if(red == 0 && green == 0 && blue == 255) { pixelcount++; } } } gtemp.dispose(); return pixelcount; } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; g2.drawImage(myshape, null, null); String buffer = "Number of pixels drawn: " + pixelDrawnCount; g2.drawString(buffer, 10, height - 50); } public static void main(String args[]) { CountPixels_FillRect panel = new CountPixels_FillRect(); pixelDrawnCount = panel.CountPixelsIn_fillRect(10,20,100,180); JFrame frame = new JFrame("Count Pixels Demo"); frame.add(panel); frame.pack(); frame.setSize(width,width); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
Output
|