I'm trying to load and a bunch of Images into a program and repaint them 60times per second.My Problem is that I get a CPU usage of over 20% and the program isn't even finished.
This is the loop that load's the Image:
for(int i = 0;i < LevelCompiler.Objectlenght;i++) {
LevelCompiler.objects[i].drawObjects(g);
}
and this is the drawObjects methode:
g.drawRect(x, y, width, height);
g.drawImage(TextureSystem.textureSystem(TextureID), x, y, width, height, null);
The textureSystem methode that load's the imgae:
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class TextureSystem {
static String TexturePath;
static BufferedImage img;
public static BufferedImage textureSystem(int tid) {
TexturePath = "/textures/Objects/SObject+" + tid + ".jpg";
try {
img = ImageIO.read(ResourceLoader.load((TexturePath)));
} catch (IOException e) {
e.printStackTrace();
}
return img;
}
}
and this is the ResourceLoader from above
import java.io.InputStream;
public final class ResourceLoader {
public static InputStream load(String path) {
InputStream input = ResourceLoader.class.getResourceAsStream(path);
if (input == null) {
System.out.println("error");
}
return input;
}
}
I assume that the high CPU usage is because I'm loading the image again and again.Any suggetions how for another methode?
I'm building a custom ASCII terminal java display for make game or application.
I currently have a problem with Swing repaint processing. Some parts of the view is paint but after a little time, they disappear from the screen. This happens quickly when you click anywhere on the screen.
A example of error :
I read the Painting in AWT and Swing but I don't find the solution.
This is the current state of the AsciiPanel state.
package ui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.LookupOp;
import java.awt.image.LookupTable;
import java.awt.image.ShortLookupTable;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.RepaintManager;
/**
* JPanel with a ASCII render system
*
* #author julien MAITRE
*
*/
public class AsciiPanel extends JPanel {
private Dimension size;
private BufferedImage[] character;
private Color defaultCharacterColor;
private Color defaultCharacterBackgroundColor;
private Dimension characterSize;
private AsciiTerminalDataCell[][] terminal;
private AsciiTerminalDataCell[][] oldTerminal;
private Image image;
private Graphics2D graphics;
private int scale;
public AsciiPanel(Dimension dimension, String tilesetFile, int characterWidth, int characterHeight) {
this(dimension, tilesetFile, characterWidth, characterHeight, 1);
}
public AsciiPanel(Dimension dimension, String tilesetFile, int characterWidth, int characterHeight, int scale) {
this.size = dimension;
this.characterSize = new Dimension(characterWidth, characterHeight);
this.scale = scale;
this.defaultCharacterColor = Color.WHITE;
this.defaultCharacterBackgroundColor = Color.BLACK;
terminal = new AsciiTerminalDataCell[size.height][size.width];
oldTerminal = new AsciiTerminalDataCell[size.height][size.width];
for(int i = 0; i < size.height; i++){
for(int j = 0; j < size.width; j++){
terminal[i][j] = new AsciiTerminalDataCell();
oldTerminal[i][j] = new AsciiTerminalDataCell();
}
}
this.setPreferredSize(new Dimension(size.width*characterSize.width*scale, size.height*characterSize.height*scale));
try {
character = new BufferedImage[256];
BufferedImage tilesets = ImageIO.read(getClass().getResource(tilesetFile));
// Recuperation of the background color
BufferedImage imageBackgroundColor = tilesets.getSubimage(0, 0, 1, 1);
int color = imageBackgroundColor.getRGB(0, 0);
Color m_characterBackgroundColor = Color.getColor(null, color);
// Modification of characters background
Image characterBackgroundColorModified = createImage(new FilteredImageSource(tilesets.getSource(), new AsciiBackgroundFilter(m_characterBackgroundColor)));
// Creation of tileset with a modification of the background color
BufferedImage tilesetsModified = new BufferedImage(tilesets.getWidth(), tilesets.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics graphicsTilesetsModified = tilesetsModified.getGraphics();
graphicsTilesetsModified.setColor(Color.BLACK);
graphicsTilesetsModified.fillRect(0, 0, tilesetsModified.getWidth(), tilesetsModified.getHeight());
// Draw in a BufferedImage for characters recuperation
graphicsTilesetsModified.drawImage(characterBackgroundColorModified, 0, 0, this);
for(int i = 0; i < 256; i++){
int x = (i%16)*characterSize.width;
int y = (i/16)*characterSize.height;
character[i] = new BufferedImage(characterSize.width, characterSize.height, BufferedImage.TYPE_INT_ARGB);
character[i].getGraphics().drawImage(tilesetsModified, 0, 0, characterSize.width, characterSize.height, x, y, x+characterSize.width, y+characterSize.height, this);
}
}
catch (IOException ex) {
Logger.getLogger(AsciiTerminal.class.getName()).log(Level.SEVERE, null, ex);
}
this.setLayout(null);
}
public void write(int positionX, int positionY, char character, Color characterColor){
this.write(positionX, positionY, character, characterColor, defaultCharacterBackgroundColor);
}
public void write(int positionX, int positionY, AsciiTerminalDataCell character){
this.write(positionX, positionY, character.data, character.dataColor, character.backgroundColor);
}
public void write(int positionX, int positionY, char character, Color characterColor, Color characterBackgroundColor){
if(positionX < 0 || positionX > size.width - 1){
throw new IllegalArgumentException("X position between [0 and "+size.width+"]");
}
if(positionY < 0 || positionY > size.height - 1){
throw new IllegalArgumentException("Y position between [0 and "+size.height+"]");
}
terminal[positionY][positionX].data = character;
terminal[positionY][positionX].dataColor = characterColor;
terminal[positionY][positionX].backgroundColor = characterBackgroundColor;
}
public void writeString(int positionX, int positionY, String string, Color characterColor){
writeString(positionX, positionY, string, characterColor, defaultCharacterBackgroundColor);
}
public void writeString(int positionX, int positionY, String string, Color characterColor, Color characterBackgroundColor){
for(char c : string.toCharArray()){
this.write(positionX, positionY, c, characterColor, characterBackgroundColor);
positionX++;
}
}
public AsciiTerminalDataCell readCurrent(int x, int y){
return this.oldTerminal[y][x];
}
public AsciiTerminalDataCell readNext(int x, int y){
return this.terminal[y][x];
}
public void clear(){
clear(0, 0, size.width, size.height);
}
public void clear(int x, int y, int width, int height){
if(x < 0 || x > size.width - 1){
throw new IllegalArgumentException("X position between [0 and "+(size.width-1)+"]");
}
if(y < 0 || y > size.height - 1){
throw new IllegalArgumentException("Y position between [0 and "+(size.height-1)+"]");
}
if(width < 1){
throw new IllegalArgumentException("Width under 1");
}
if(height < 1){
throw new IllegalArgumentException("Height under 1");
}
if(width+x > size.width || height+y > size.height){
throw new IllegalArgumentException("Clear over the terminal");
}
for(int i = y; i < y + height; i++){
for(int j = x; j < x + width; j++) {
write(j, i, (char)0, defaultCharacterColor, defaultCharacterBackgroundColor);
}
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(image == null) {
image = this.createImage(this.getPreferredSize().width, this.getPreferredSize().height);
graphics = (Graphics2D)image.getGraphics();
graphics.setColor(defaultCharacterBackgroundColor);
graphics.fillRect(0, 0, this.getWidth(), this.getHeight());
}
for(Component component : getComponents()) {
component.paint(graphics);
}
for(int i = 0; i < size.height; i++){
for(int j = 0; j < size.width; j++){
if( terminal[i][j].data == oldTerminal[i][j].data &&
terminal[i][j].dataColor.equals(oldTerminal[i][j].dataColor) &&
terminal[i][j].backgroundColor.equals(oldTerminal[i][j].backgroundColor)) {
continue;
}
LookupOp lookupOp = setColorCharacter(terminal[i][j].backgroundColor, terminal[i][j].dataColor);
graphics.drawImage(lookupOp.filter(character[terminal[i][j].data], null), j*characterSize.width*scale, i*characterSize.height*scale, characterSize.width*scale, characterSize.height*scale, this);
oldTerminal[i][j].data = terminal[i][j].data;
oldTerminal[i][j].dataColor = terminal[i][j].dataColor;
oldTerminal[i][j].backgroundColor = terminal[i][j].backgroundColor;
}
}
g.drawImage(image, 0, 0, this);
}
private LookupOp setColorCharacter(Color bgColor, Color fgColor){
short[] red = new short[256];
short[] green = new short[256];
short[] blue = new short[256];
short[] alpha = new short[256];
// Recuperation of compound colors of foreground character color
short dcr = (short) fgColor.getRed();
short dcg = (short) fgColor.getGreen();
short dcb = (short) fgColor.getBlue();
// Recuperation of compound colors of background character color
short bgr = (short) bgColor.getRed();
short bgg = (short) bgColor.getGreen();
short bgb = (short) bgColor.getBlue();
for(short j = 0; j < 256; j++){
// if is foreground color
if(j != 0){
/**
* Calculation of j*255/dcr .
* Cross product
* dcr = 180 255
* j = ? X
* Distribute the requested color [0 to 255] on the character color [0 to X]
*/
// Red
if(dcr != 0){
red[j] = (short)(j*dcr/255);
}
else{
red[j] = 0;
}
// green
if(dcg != 0){
green[j] = (short)(j*dcg/255);
}
else{
green[j] = 0;
}
// Blue
if( dcb != 0){
blue[j] = (short)(j*dcb/255);
}
else{
blue[j] = 0;
}
// Alpha
alpha[j] = 255;
}
// else is background color
else {
red[j] = bgr;
green[j] = bgg;
blue[j] = bgb;
alpha[j] = 255;
}
}
short[][] data = new short[][]{red, green, blue, alpha};
LookupTable lookupTable = new ShortLookupTable(0, data);
LookupOp lookupOp = new LookupOp(lookupTable, null);
return lookupOp;
}
public Color getDefaultCharacterColor(){
return this.defaultCharacterColor;
}
public void setDefaultCharacterColor(Color color){
this.defaultCharacterColor = color;
}
public Color getDefaultCharacterBackgroundColor() {
return defaultCharacterBackgroundColor;
}
public void setDefaultCharacterBackgroundColor(Color defaultCharacterBackgroundColor) {
this.defaultCharacterBackgroundColor = defaultCharacterBackgroundColor;
}
public Dimension getCharacterSize() {
return characterSize;
}
public int getScale() {
return scale;
}
public AsciiTerminalDataCell getCell(int x, int y) {
return terminal[y][x];
}
}
ChiptuneTracker main class :
package main;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URISyntaxException;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import ui.AsciiPanel;
import ui.AsciiTerminalDataCell;
import ui.CustomAsciiTerminal;
public class ChiptuneTracker {
public static final String TITLE = "ChiptuneTracker";
public static final int WINDOW_WIDTH = 29;
public static final int WINDOW_HEIGHT = 18;
public static final String TILESET_FILE = "/assets/wanderlust.png";
public static final String ICON_FILE = "/assets/icon.png";
public static final int CHARACTER_WIDTH = 12;
public static final int CHARACTER_HEIGHT = 12;
public static final int TARGET_FPS = 60;
public static final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;
public static final int SCALE = 3;
public static final boolean CUSTOM_WINDOW = true;
private static ChiptuneTracker instance = new ChiptuneTracker();
private CustomAsciiTerminal asciiTerminal;
private AsciiPanel asciiPanel;
private boolean initSampleView = true;
private boolean initPatternView = true;
private Data data = new Data();
private DataManager dataManager;
private boolean changeData = false;
private Chanels chanels = new Chanels();
private View currentView;
private MenuView menuView;
private SampleView sampleView;
private PatternView patternView;
private ChiptuneTracker() {
asciiTerminal = new CustomAsciiTerminal(TITLE, new Dimension(WINDOW_WIDTH, WINDOW_HEIGHT), TILESET_FILE, CHARACTER_WIDTH, CHARACTER_HEIGHT, SCALE, ICON_FILE, CUSTOM_WINDOW);
asciiPanel = asciiTerminal.getAsciiPanel();
asciiPanel.setDefaultCharacterBackgroundColor(Color.DARK_GRAY);
asciiPanel.setDefaultCharacterColor(Color.WHITE);
dataManager = new DataManager();
}
public void init() {
menuView = new MenuView(this);
sampleView = new SampleView(this);
patternView = new PatternView(this);
changeView(sampleView);
}
public void run() {
long lastLoopTime = System.nanoTime();
boolean stopRender = true;
while(true) {
long now = System.nanoTime();
double updateLength = now - lastLoopTime;
lastLoopTime = now;
double delta = updateLength / ChiptuneTracker.OPTIMAL_TIME;
// Screenshot
KeyEvent event = asciiTerminal.getEvent();
if(event != null) {
if(event.getKeyCode() == KeyEvent.VK_F12) {
try {
BufferedImage image = new BufferedImage(WINDOW_WIDTH * CHARACTER_WIDTH * SCALE, WINDOW_HEIGHT * CHARACTER_HEIGHT * SCALE, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
asciiPanel.paint(graphics);
boolean save = false;
int i = 0;
do {
File file = new File("screenshot-" + i + ".png");
if(!file.exists()) {
ImageIO.write(image, "PNG", file);
save = true;
}
i++;
} while(!save);
} catch (Exception e) {
JOptionPane.showMessageDialog(ChiptuneTracker.getInstance().getAsciiTerminal(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
finally {
asciiTerminal.setEvent(null);
}
}
}
// Update
currentView.update(delta);
chanels.update();
// Paint
asciiPanel.clear();
currentView.paint();
asciiTerminal.revalidate();
asciiTerminal.repaint();
try {
long value = (lastLoopTime - System.nanoTime() + ChiptuneTracker.OPTIMAL_TIME) / 1000000;
if(value > 0) {
Thread.sleep(value);
}
else {
Thread.sleep(5);
}
} catch (InterruptedException e) {
}
}
}
public void changeView(View nextView) {
if(currentView != null) {
currentView.quit();
}
currentView = nextView;
asciiPanel.clear();
currentView.init();
}
public static ChiptuneTracker getInstance() {
return instance;
}
public CustomAsciiTerminal getAsciiTerminal() {
return asciiTerminal;
}
public AsciiPanel getAsciiPanel() {
return asciiPanel;
}
public boolean isInitPatternView() {
return initPatternView;
}
public boolean isInitSampleView() {
return initSampleView;
}
public void setInitPatternView(boolean initPatternView) {
this.initPatternView = initPatternView;
}
public void setInitSampleView(boolean initSampleView) {
this.initSampleView = initSampleView;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public DataManager getDataManager() {
return dataManager;
}
public boolean isChangeData() {
return changeData;
}
public void setChangeData(boolean changeData) {
this.changeData = changeData;
}
public Chanels getChanels() {
return chanels;
}
public MenuView getMenuView() {
return menuView;
}
public SampleView getSampleView() {
return sampleView;
}
public PatternView getPatternView() {
return patternView;
}
public static void main(String[] args) {
ChiptuneTracker chiptuneTracker = ChiptuneTracker.getInstance();
chiptuneTracker.init();
chiptuneTracker.run();
}
}
Is there any solution to resolve that?
Thanks!
As you will see in the code, I've tried to make a custom sprite class, but for some reason, the values of the variables "disappear" , and if (as you will see) isSprite is true, then even the mainframe won't appear/won't be visible, and it will just run in the background until you stop it manually.
Here is the code of the class:
package testowhat;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Sprite extends Component {
Sprite(String image1) throws IOException, InterruptedException{
playerConstructor(image1);
}
Integer imgPosX; Integer imgPosY;
Integer divideSize2; Integer divideSize1;
Integer Height; Integer Width;
Integer numberOfSpriteCells, numberOfSpriteLayers, numberOfCellsInALine, heightOfCells, widthOfCells, countingNumber1, countingNumber2;
BufferedImage picture;
Boolean isSprite;
String image;
JPanel picturePanel = new JPanel() {
public void paint(Graphics g) {
g.drawImage(picture.getScaledInstance(picture.getWidth()/divideSize1, picture.getHeight()/divideSize2, Image.SCALE_DEFAULT), imgPosX, imgPosY, null);
}
};
private void playerConstructor(String image) throws IOException, InterruptedException {
try {
picture = ImageIO.read(new File(image));
} catch (IOException ex) {System.out.println("File is missing.");}
//----------------------------------------------------------------------
Height = picture.getHeight()+10;
Width = picture.getWidth()+10;
//----------------------------------------------------------------------
picturePanel.setLocation(this.getLocation());
picturePanel.setSize(this.getHeight(), this.getWidth());
//----------------------------------------------------------------------
picturePanel.setMinimumSize(new Dimension(Height, Width));
picturePanel.setMaximumSize(new Dimension(Height, Width));
//----------------------------------------------------------------------
if (this.isVisible() == true) {
picturePanel.setVisible(true);
}
//----------------------------------------------------------------------
this.countingNumber1 = 0;
checkThem();
justDoIt();
}
//--------------------------------------------------------------------------
private void checkThem() {
if (isSprite == null) {
isSprite = false;
}
if (imgPosX == null) {
imgPosX = 0;
imgPosY = 0;
}
if (imgPosY == null) {
imgPosX = 0;
imgPosY = 0;
}
if (numberOfSpriteCells == null) {
numberOfSpriteCells = 6;
}
if (widthOfCells == null) {
widthOfCells = 103;
}
if (heightOfCells == null) {
heightOfCells = 89;
}
if (numberOfSpriteLayers == null) {
numberOfSpriteLayers = 2;
}
}
//--------------------------------------------------------------------------
private void justDoIt() throws InterruptedException {
if (isSprite == true) {
for (countingNumber2=1; countingNumber2<7; countingNumber2++) {
doChange();
Thread.sleep(100);
this.repaint();
this.picturePanel.repaint();
if (countingNumber2 <= 7) {
countingNumber2 = 1;
}
}
}
}
//--------------------------------------------------------------------------
private void doChange() {
imgPosX = imgPosX - widthOfCells;
countingNumber1 = countingNumber1++;
repaint();
picturePanel.repaint();
if (countingNumber1==numberOfSpriteCells/numberOfSpriteLayers) {
imgPosY = imgPosY - heightOfCells;
imgPosX = 0;
}
if (countingNumber1 == numberOfSpriteCells) {
countingNumber1 = 0;
imgPosX = 0;
imgPosY = 0;
repaint();
picturePanel.repaint();
}
}
}
As a sidenote:
I. In the first "version" of the code the doChange() procedure was in
another class.
II. The setbounds of the picture, and the picturepanel are declared in
another class, but is connected.
III. For some reason most of the set variables seem to lose their
values
IV. I've already had a nullPointerException problem with inserting the
doChange() procedure, so I'm guessing that maybe that's the one which
causes these problems.
The results of running the program:
If the isSprite is set to false then:
It runs smoothly and displays the part of the picture we (I) wanted.
and if it is set to true:
Nothing happens, it runs, but nothing will appear, it is just not working correctly.
I've coded up a program that can read rgb values off of a jpg file, but when i test it with a solid color i'm getting rgb results that are slightly inaccurate. Does anyone know if its my code or if its java that is inaccurate?
RGB
red=64 green=0 blue=128
RESULT
red=65 green=0 blue=128
CODE
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.ArrayList;
import javax.imageio.*;
public class Program {
public int[][] rgbValues;
public File imagePath = new File("src/image3.jpg");
public BufferedImage image;
public Program() throws IOException{
image = ImageIO.read(imagePath);
rgbValues = new int[image.getWidth()][image.getHeight()];
}
public void run() throws IOException{
getData();
analyzeData();
}
private void getData() throws IOException{
for (int y = 0; y < image.getHeight(); y++){
for (int x = 0; x < image.getWidth(); x++){
rgbValues[y][x] = image.getRGB(x, y);
}
}
}
private void analyzeData() throws IOException{
boolean f = image.getAlphaRaster() != null;
Color color = new Color(rgbValues[10][10], f);
System.out.println(color.getRed());
System.out.println(color.getGreen());
System.out.println(color.getBlue());
}
}
Code seems correct and results as well, Paint says the image is also (65,0,128)
Okay, so my friend and I are making are a game that requires some pixel analysis for the rectangles, and I wrote the code to analyze the rectangles, and It works swimmingly, However, when I try to draw the bufferedImage it doesn't show up. The main issue is that my java class has never taught us how to use Jframes, and I don't want to change my code to accommodate:
// Threaded Applet Template that works with Macs
// Import section
// Use this section to add additional libaries for use in your program.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.awt.Toolkit;
import javax.imageio.*;
import javax.swing.*;
import java.awt.image.*;
import java.io.*;
// This begins the class definition.
// Notice that this is a "world". You can tell since it extends Applet.
// It also implement Runnable which allows it to be and use threads.
public class PixelAnalyzetest extends Applet implements Runnable
{
//variable declaration section
// public datatype variablename
public int xTitle;
public int yTitle;
public Analyzer analyzer;
public BufferedImage test;
public Image itest;
public boolean analyzeonce=true;
//declare your Hero object here
//Sets up a Thread called thread
Thread thread;
// Method definition section
// init() is the first method an Applet runs when started
public void init()
{
//Initialize variables
xTitle=10;
yTitle=10;
BufferedImage test = new BufferedImage(1200,1200, BufferedImage.TYPE_INT_ARGB);
//test = getImage(getDocumentBase(),"test.png");
System.out.println("the width of the image is: "+test.getWidth(this));
try{
test = ImageIO.read(new File("test.png"));
} catch(IOException e) {};
//itest=test.getAsBufferedImage();
analyzer = new Analyzer(test, 5);
//construct objects
//construct your hero here!
//Set up the thread
//These should be the LAST lines in your init( ) method.
thread = new Thread(this); //constructs a new thread
thread.start(); //starts the thread
}//init()
// paint() is used to display things on the screen
public void paint(Graphics g)
{
setSize(1200,1200);
//Put the title on the screen.
/*for(int x=0;x<test.getWidth();x++)
{
for(int y=0;y<test.getHeight();y++)
{
BufferedImage.setRGB(x,y,analyzer.pictureRGB[x][y]);
}
}*/
g.drawImage(test,0,0,1200,1200,this);
//draw your hero's name here using g.drawString( )
}// paint()
// every thread needs a run method
// this is what the thread will do
public void run() {
// this thread loop forever and runs the paint method and then sleeps.
while(true)
{
//put what you want your program to do here.
//move your hero here by calling its move() method.
if(analyzeonce==true)
{
analyzer.analyzelines();
analyzeonce=false;
}
repaint(); // run the paint method.
//sleep
try {
thread.sleep(100);
}
catch (Exception e){ }
}//while
}// run()
}
Now my analyzer class:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.awt.Toolkit;
public class Analyzer
{
public int[][] pictureRGB;
//VARIABLE DECLARATION SECTION
//Here's where you state which variables you are going to use.
public String name; //use this format public datatype variablename;
public boolean isAlive;
public int health;
public int strength;
public String theGlove;
public int dx, dy;
public BufferedImage analyzing, bgrab;
public int imagewidth, imageheight;
public int linecounter = 0;
public int boxcounter = 0;
public boolean endline = false;
public Line lines[];
public Box boxes[];
public int totalboxes;
public boolean donean = false;
// METHOD DEFINITION SECTION
// Constructor Definition
// A constructor "builds" the object when called and give the variable initial values.
// This constructor build Heroes with all the same initial values.
public Analyzer(BufferedImage grab, int xtotalboxes)
{
//BufferedImage bgrab = (BufferedImage) grab;
//bgrab = new BufferedImage(1200,1200, BufferedImage.TYPE_INT_ARGB);
//bgrab.getGraphics().drawImage(grab,0,0,bgrab.getWidth(),bgrab.getHeight(),null);
analyzing = grab;
totalboxes = xtotalboxes;
imagewidth=analyzing.getWidth();
System.out.println(imagewidth+" Is the image's Width");
imageheight=analyzing.getHeight();
System.out.println(imagewidth+" Is the image's Height");
pictureRGB= new int[imagewidth] [imageheight];
lines = new Line[10];
boxes = new Box[20];
isAlive = true;
health = 200;
strength = 20;
for(int xpos = 1; xpos<imagewidth-1;xpos++)
{
for(int ypos = 1; ypos<imageheight-1; ypos++)
{
pictureRGB[xpos][ypos]=analyzing.getRGB(xpos,ypos);
//System.out.println(pictureRGB[xpos][ypos]);
}
}
}
public void analyzelines()
{
for(boxcounter=0; boxcounter<boxes.length; boxcounter++)
{
int tempx = 0;
int tempy = 0;
int tempw = 0;
int temph = 0;
//int pxpos = 0;
//int pypos = 0;
boolean startline=false;
boolean foundw = false;
boolean foundh = false;
if(donean==false)
{
for(int ypos = 1; ypos<imageheight-1; ypos++)
{
for(int xpos = 1; xpos<imagewidth-1;xpos++)
{
if(boxcounter>0)
{
if(pictureRGB[xpos][ypos]==-3584 && startline==false && boxes[boxcounter-1].rect.contains(new Point(xpos,ypos))==false && boxes[boxcounter-1].rect.intersects(new Rectangle(xpos-2,ypos-2,4,4))==false && isEqual(new Rectangle(xpos-2,ypos-2,4,4))==false)
{
System.out.println("--------------------------------START BOX --------------");
System.out.println("The top left corner of the box is: ("+xpos+","+ypos+")");
startline=true;
tempx=xpos;
tempy=ypos;
//System.out.println(tempx+"<<TEMPX TEMPY>>"+tempy);
}
if(startline==true && pictureRGB[xpos+1][ypos]!=pictureRGB[xpos][ypos] && foundw==false && foundh==false && boxes[boxcounter-1].rect.contains(new Point(xpos,ypos))==false && isEqual(new Rectangle(xpos-2,ypos-2,4,4))==false)
{
tempw=xpos-tempx;
System.out.println("XPOS EQ = "+xpos+" - "+tempx+" = "+ tempw);
foundw = true;
//System.out.println(tempw+"<<TEMPw TEMPx>>"+tempx+"<<<<XPOS>>>>>>>>>>>>>"+xpos);
}
if(startline==true && pictureRGB[xpos][ypos+1]!=pictureRGB[xpos][ypos] && foundh==false && foundw==true && boxes[boxcounter-1].rect.contains(new Point(xpos,ypos))==false && pictureRGB[xpos-1][ypos]==pictureRGB[xpos][ypos] && pictureRGB[xpos+1][ypos]!=pictureRGB[xpos][ypos] && isEqual(new Rectangle(xpos-2,ypos-2,4,4))==false)
{
temph=ypos-tempy;
System.out.println("YPOS EQ = "+ypos+" - "+tempy+" = "+ temph);
foundh=true;
System.out.println("The Width is: "+tempw+" The height is: "+temph+" boxcounter="+boxcounter);
boxes[boxcounter]= new Box(tempx, tempy, tempw, temph);
System.out.println("--------------------------------NEXT BOX ---------------");
//System.out.println("BOX WIDTH"+boxes[boxcounter].width + "BOX COUNTER=="+boxcounter);
}
}
if(boxcounter==0)
{
if(pictureRGB[xpos][ypos]==-3584 && startline==false)
{
System.out.println("The top left corner of the box is: ("+xpos+","+ypos+")");
startline=true;
tempx=xpos;
tempy=ypos;
}
if(startline==true && pictureRGB[xpos+1][ypos]!=pictureRGB[xpos][ypos] && foundw==false && foundh==false)
{
tempw=xpos-tempx;
foundw = true;
}
if(startline==true && pictureRGB[xpos][ypos+1]!=pictureRGB[xpos][ypos] && foundh==false && foundw==true)
{
temph=ypos-tempy;
foundh=true;
System.out.println("The Width is: "+tempw+" The height is: "+temph+" boxcounter="+boxcounter);
boxes[boxcounter]= new Box(tempx, tempy, tempw, temph);
//System.out.println("BOX WIDTH"+boxes[boxcounter].width);
}
}
}
}
if(boxcounter>=(totalboxes))
{
donean=true;
}
}
//System.out.println("The black lines width is: "+(lines[linecounter].endx-lines[linecounter].startx));
}
}
public boolean isEqual(Rectangle c1)
{
boolean returned = false;
for(int i = 0; i<boxcounter; i++)
{
if(c1.intersects(boxes[i].rect) || boxes[i].rect.contains(new Point(c1.x, c1.y)))
{
returned=true;
}
}
return(returned);
}
/*
public static BufferedImage toBufferedImage(Image img)
{
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}
// Create a buffered image with transparency
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
}
*/
public void move()
{
}
//Other methods
//You can define what this type of object can do here.
}
my line and box classes are very straight forward just some classes i made with xposes and yposes, width's and heights