Is there a way in java to get the vertices of a font so they can be displayed as particles in java?
like so:
Yes, there's a way. It's not trivial. I wrote this class as part of a marquee GUI.
Pay particular attention to the getTextPixels method.
package com.ggl.marquee.model;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
public class MarqueeFont {
private static final boolean DEBUG = false;
private int fontHeight;
private Font font;
public MarqueeFont(Font font) {
this.font = font;
FontRenderContext frc = new FontRenderContext(null, true, true);
Rectangle2D r2D = font.getStringBounds("HgH", frc);
this.fontHeight = (int) Math.round(r2D.getHeight());
if (DEBUG) {
System.out.println(font.getFamily() + " " + fontHeight + " pixels");
}
}
public boolean[][] getTextPixels(String s) {
FontRenderContext frc = new FontRenderContext(null, true, true);
Rectangle2D r2D = font.getStringBounds(s, frc);
int rWidth = (int) Math.round(r2D.getWidth());
int rHeight = (int) Math.round(r2D.getHeight());
int rX = (int) Math.round(r2D.getX());
int rY = (int) Math.round(r2D.getY());
if (DEBUG) {
System.out.print(s);
System.out.print(", rWidth = " + rWidth);
System.out.print(", rHeight = " + rHeight);
System.out.println(", rX = " + rX + ", rY = " + rY);
}
BufferedImage bi = generateCharacterImage(rX, -rY, rWidth, rHeight, s);
int[][] pixels = convertTo2D(bi);
if (DEBUG) {
displayPixels(pixels);
}
return createTextPixels(pixels);
}
private BufferedImage generateCharacterImage(int x, int y, int width,
int height, String string) {
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.setFont(font);
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.drawString(string, x, y);
return bi;
}
private int[][] convertTo2D(BufferedImage image) {
final int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer())
.getData();
final int width = image.getWidth();
final int height = image.getHeight();
int[][] result = new int[height][width];
int row = 0;
int col = 0;
for (int pixel = 0; pixel < pixels.length; pixel++) {
result[row][col] = pixels[pixel];
col++;
if (col == width) {
col = 0;
row++;
}
}
return result;
}
private void displayPixels(int[][] pixels) {
for (int i = 0; i < pixels.length; i++) {
String s = String.format("%03d", (i + 1));
System.out.print(s + ". ");
for (int j = 0; j < pixels[i].length; j++) {
if (pixels[i][j] == -1) {
System.out.print(" ");
} else {
System.out.print("X ");
}
}
System.out.println("");
}
}
private boolean[][] createTextPixels(int[][] pixels) {
// The int array pixels is in column, row order.
// We have to flip the array and produce the output
// in row, column order.
if (DEBUG) {
System.out.println(pixels[0].length + "x" + pixels.length);
}
boolean[][] textPixels = new boolean[pixels[0].length][pixels.length];
for (int i = 0; i < pixels.length; i++) {
for (int j = 0; j < pixels[i].length; j++) {
if (pixels[i][j] == -1) {
textPixels[j][i] = false;
} else {
textPixels[j][i] = true;
}
}
}
return textPixels;
}
public Font getFont() {
return font;
}
public int getFontHeight() {
return fontHeight;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(font.getFamily());
builder.append(", ");
builder.append(getStyleText());
builder.append(", ");
builder.append(font.getSize());
builder.append(" pixels");
return builder.toString();
}
private StringBuilder getStyleText() {
StringBuilder builder = new StringBuilder();
int style = font.getStyle();
if (style == Font.PLAIN) {
builder.append("normal");
} else if (style == Font.BOLD) {
builder.append("bold");
} else if (style == Font.ITALIC) {
builder.append("italic");
} else if (style == (Font.BOLD + Font.ITALIC)) {
builder.append("bold italic");
} else {
builder.append("unknown style");
}
return builder;
}
}
Related
I am trying to create a component for libgdx which can output text in a manner equal to what html would do with a <p align=”justify”> ... </p>.
My idea was to add some custom component which can achieve this by adjusting the relative x and y coordinations of the components.
import java.util.ArrayList;
import java.util.List;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup;
import com.badlogic.gdx.utils.Align;
public class Paragraph extends WidgetGroup {
private Label space;
public Paragraph(String text, float width, LabelStyle style) {
super();
setWidth(width);
this.space = new Label(" ", style);
this.space.pack();
String[] words = text.split(" ");
for (String word : words) {
Label label = new Label(word, style);
label.pack();
addActor(label);
}
}
public void layout () {
float size = 0;
List<Actor> elements = new ArrayList<Actor>();
float x = getX(Align.topLeft);
float y = getY(Align.topLeft);
for (Actor actor : this.getChildren().items) {
if (actor != null) {
if (elements.isEmpty()) {
elements.add(actor);
size = actor.getWidth();
} else {
if (size + space.getWidth() + actor.getWidth() <= this.getWidth()) {
elements.add(actor);
size += (space.getWidth() + actor.getWidth());
} else {
float spacing = space.getWidth() + ((getWidth() - size) / elements.size());
Actor element = elements.get(0);
element.setPosition(x, y, Align.topLeft);
x += element.getWidth();
for (int i = 1; i < elements.size(); i++) {
element = elements.get(i);
element.setPosition(x + spacing, y, Align.topLeft);
x += (spacing + element.getWidth());
}
// new line
elements.clear();
x = getX(Align.topLeft);
y += (this.space.getHeight() * 1.5);
elements.add(actor);
size = actor.getWidth();
}
}
}
}
if (elements.isEmpty() == false) {
float spacing = space.getWidth();
Actor element = elements.get(0);
element.setPosition(x, y, Align.topLeft);
x += element.getWidth();
for (int i = 1; i < elements.size(); i++) {
element = elements.get(i);
element.setPosition(x + spacing, y, Align.topLeft);
x += (spacing + element.getWidth());
}
}
}
}
My problem is that the x and y coordinate I retrieve with getX(Align.topLeft) & getY(Align.topLeft) always returns (0,0)
instead of the real coordinates on the stage.
Component structure looks like this:
Stage
+ Container
+ Table
+ ScrollPane
+ Table
+ Table
+ Paragraph
+ Paragraph
+ Paragraph
+ Paragraph
+ Image
So the end result is that all the text contained in the different paragraphs is drawn on top of each other. Not on position (0,0), but on the same position inside of the surrounding table.
I figured it out myself.
Seems it was a bad idea to override the layout method for that.
I now call a different method from the constructor.
Also I messed up with the x and y coordinates, so I had to rewrite that method.
Ps.:
I adjusted the question as well, as I figured out the solution, it was
not really about the x and y coodinates of the widget group.
import java.util.ArrayList;
import java.util.List;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup;
import com.badlogic.gdx.utils.Align;
public class Paragraph extends WidgetGroup {
private static final class RowData {
final List<Actor> elements;
final float size;
final boolean lastRow;
RowData(List<Actor> elements, float size, boolean lastRow) {
this.elements = elements;
this.size = size;
this.lastRow = lastRow;
}
static RowData createNewRow(List<Actor> elements, float size) {
return new RowData(elements, size, false);
}
static RowData createLastRow(List<Actor> elements, float size) {
return new RowData(elements, size, true);
}
}
private Label space;
public Paragraph(String text, float width, LabelStyle style) {
super();
setWidth(width);
this.space = new Label(" ", style);
this.space.pack();
String[] words = text.split(" ");
for (String word : words) {
Label label = new Label(word, style);
label.pack();
addActor(label);
}
arrangeActors();
}
private void arrangeActors() {
float size = 0;
float height = space.getHeight();
List<RowData> rows = new ArrayList<RowData>();
List<Actor> elements = new ArrayList<Actor>();
Actor[] actors = this.getChildren().begin();
for (Actor actor : actors) {
if (actor != null) {
if (elements.isEmpty()) {
elements.add(actor);
size = actor.getWidth();
} else if (size + space.getWidth() + actor.getWidth() <= this.getWidth()) {
elements.add(actor);
size += (space.getWidth() + actor.getWidth());
} else {
rows.add(RowData.createNewRow(elements, size));
elements = new ArrayList<Actor>();
height += space.getHeight();
elements.add(actor);
size = actor.getWidth();
}
}
}
this.getChildren().end();
rows.add(RowData.createLastRow(elements, size));
height += space.getHeight();
setHeight(height);
float y = height;
for (RowData data : rows) {
float spacing = space.getWidth();
if (data.lastRow == false) {
spacing += ((getWidth() - data.size) / data.elements.size());
}
Actor element = data.elements.get(0);
element.setPosition(0, y, Align.topLeft);
float x = element.getWidth();
for (int i = 1; i < data.elements.size(); i++) {
element = data.elements.get(i);
element.setPosition(x + spacing, y, Align.topLeft);
x += (spacing + element.getWidth());
}
y -= this.space.getHeight();
}
}
#Override
public float getPrefWidth () {
return getWidth();
}
#Override
public float getPrefHeight () {
return getHeight();
}
}
I want to crop all four side white spaces.
the easiest way to auto crop the white border out of an image in java? Thanks in advance...
public class TrimWhite {
public class TrimWhite {
private BufferedImage img;
public TrimWhite(File input) {
try {
img = ImageIO.read(input);
} catch (IOException e) {
throw new RuntimeException( "Problem reading image", e );
}
}
public void trim() {
int width = getTrimmedWidth();
int height = getTrimmedHeight();
BufferedImage newImg = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = newImg.createGraphics();
g.drawImage( img, 0, 0, null );
img = newImg;
}
public void write(File f) {
try {
ImageIO.write(img, "bmp", f);
} catch (IOException e) {
throw new RuntimeException( "Problem writing image", e );
}
}
private int getTrimmedWidth() {
int height = this.img.getHeight();
int width = this.img.getWidth();
int trimmedWidth = 0;
for(int i = 0; i < height; i++) {
for(int j = width - 1; j >= 0; j--) {
if(img.getRGB(j, i) != Color.WHITE.getRGB() &&
j > trimmedWidth) {
trimmedWidth = j;
break;
}
}
}
return trimmedWidth;
}
private int getTrimmedHeight() {
int width = this.img.getWidth();
int height = this.img.getHeight();
int trimmedHeight = 0;
for(int i = 0; i < width; i++) {
for(int j = height - 1; j >= 0; j--) {
if(img.getRGB(i, j) != Color.WHITE.getRGB() &&
j > trimmedHeight) {
trimmedHeight = j;
break;
}
}
}
return trimmedHeight;
}
public static void main(String[] args) {
TrimWhite trim = new TrimWhite(new File("C:\\Users\\Administrator\\Desktop\\New folder (2)\\Untitled.png"));
trim.trim();
trim.write(new File("C:\\Users\\Administrator\\Desktop\\New folder (2)\\test.png"));
}
}
}
I want output must crop all four side white spaces please help!
I am trying to make an image to text program that converts a 0-255 value to a character that matches it (visually). The important thing here is having all characters the same width so in a text editor the text is square...
basically I want all characters from 32-4000 that have the same width as 'X' so I can use 'Q' but not '|' (this font is mono tho so there is no difference)
I am using the Unifont font.
What I have currently works, but I want to supply a general range of unicode characters that are all the same size (so it looks good in text at the end)
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
Color fntC = new Color(255, 255, 255);
Graphics2D g = img.createGraphics();
g.setFont(f);
FontMetrics fm = g.getFontMetrics();
for (int i = 32; i <= 4000/*126*/; i++) { //33 126
if (fm.charWidth((char)i) == fm.charWidth('X') && Character.isLetter(i))
dictionary.add(new letter((char) i, getValue((char) i)));
}
This code works pretty well, but I still get characters like 'ȷ' that has a smaller width in the text editor but is treated as the same width as 'X' according to font metrics (I'm using Courier new since that's the default of Notepad++)
MOAR CODE:
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
public class MainImageToText {
public static void main(String[] args) {
CharDictionary cd = new CharDictionary(new Font("Unifont", 1, 20));
JFileChooser chooser = new JFileChooser();
/*FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG Images", "png");
chooser.setFileFilter(filter);*/
chooser.setCurrentDirectory(new File(System.getProperty("user.home"), "Desktop"));
int returnVal = chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("\nYou chose to open this file: " + f);
File output = new File(f.getParentFile(), "$output.txt");
saveTextFile(output, ImageToText(f, cd));
}
}
static String ImageToText(File f, CharDictionary cd) {
BufferedImage img = null;
String text = "";
try {
img = ImageIO.read(f);
} catch (IOException e) {
e.printStackTrace();
}
int w = img.getWidth();
int h = img.getHeight();
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
Color col = new Color(img.getRGB(x, y));
int red = col.getRed();
int green = col.getGreen();
int blue = col.getBlue();
int finalAverage = (red + green + blue) / 3;
text += cd.getDictionaryLetter(finalAverage);
System.out.println(x + ", " + y);
}
text += "\n";
}
cd.debugPrintDictionary();
// System.out.println(text);
return text;
}
static void saveTextFile(File f, String s) {
File desktop = new File(System.getProperty("user.home"), "Desktop");
File outputfile = new File(desktop.toString() + "\\" + "file.txt");
try {
System.out.println("creating file...");
PrintWriter out = new PrintWriter(outputfile, "UTF-8");
out.write(s);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Saved to: " + f);
}
}
class letter {
public String c;
public int val;
letter(String ch, int dub) {
c = ch;
val = dub;
}
public char getChar() {
Random rand = new Random();
return c.charAt(rand.nextInt(c.length()));
}
public void addChar(char ch) {
c += ch;
}
public void addChar(String ch) {
c += ch;
}
}
class LetterComparator implements Comparator<letter> {
#Override
public int compare(letter a, letter b) {
return (a.val - b.val); // *100 for more precision
}
}
class CharDictionary {
private Font f;
private List<letter> dictionary = new ArrayList<letter>();
CharDictionary(Font font) {
f = font;
createDictionary();
}
public void createDictionary() {
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
Color fntC = new Color(255, 255, 255);
Graphics2D g = img.createGraphics();
g.setFont(f);
FontMetrics fm = g.getFontMetrics();
dictionary.add(new letter(" ", getValue(' ')));
for (int i = 32; i <= 65000; i++) { //33 126
if (fm.charWidth(i) == fm.charWidth('X') && !Character.isWhitespace(i))
dictionary.add(new letter((char) i + "", getValue((char) i)));
}
sort();
compact();
}
public void sort() {
Collections.sort(dictionary, new LetterComparator());
}
public void compact() {
int val;
for (int i = dictionary.size()-1; i > 0 ; i--) {
val = dictionary.get(i).val;
if (val == dictionary.get(i-1).val) {
dictionary.get(i-1).addChar(dictionary.get(i).c);
dictionary.remove(i);
}
}
}
public void debugPrintDictionary() {
for (int i = 0; i < dictionary.size(); i++) {
System.out.println("Char: " + dictionary.get(i).c + " Value: " + dictionary.get(i).val);
}
}
/*public int getIndexofVal(int n) {
return null;
}*/
public char getDictionaryLetter(int val) {
for (int i = 0; i < dictionary.size(); i++) {
int charvalue = dictionary.get(i).val;
if (charvalue >= 255-val) {//inverted here
return dictionary.get(i).getChar();
}
}
return dictionary.get(dictionary.size() - 1).getChar(); /// PROBLEM HERE
}
public int getValue(char c) {
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
Color fntC = new Color(255, 255, 255);
Graphics2D g = img.createGraphics();
g.setFont(f);
FontMetrics fm = g.getFontMetrics();
int width = fm.charWidth(c);
int height = fm.getAscent()+ fm.getDescent(); // too big
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g = img.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(fntC);
g.setFont(f);
// g.fill
g.drawString(c + "", 0, fm.getAscent());
int w = img.getWidth();
int h = img.getHeight();
double finalAverage = 0;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
Color col = new Color(img.getRGB(x, y));
int red = col.getRed();
int green = col.getGreen();
int blue = col.getBlue();
finalAverage += (red + green + blue) / 3;
}
}
finalAverage /= w * h;
/*try {
File desktop = new File(System.getProperty("user.home"), "Desktop");
File outputfile = new File(desktop.toString() + "\\letters\\" + (int) c + ".png");
ImageIO.write(img, "png", outputfile);
} catch (IOException e) {
}*/
return (int)finalAverage;
}
}
I am a beginner to Java. Currently I want to analyze two similar images and check whether the images have different pixel values at position 2 and 4. I already develop some codes but when running it, the code produces error and it doesn't looping and check for all pixel values on both images.
For example, in the 9th pixel, image B pixel value at position 2 and 4 are not the same as image A pixel value. Then, whenever the code notices a differences between both images pixel value it will output the statement saying the pixel are not the same.
Here's the code:
public class getPixelRGB1
{
private static String[][] img_hex2;
private static String[][] img_hex4;
private static String[][] img2_hex2;
private static String[][] img2_hex4;
public static void main(String[] args) throws IOException
{
FileInputStream image = null;
FileInputStream image2 = null;
getPixelData1 newPD = new getPixelData1();
compareHexaRGB hexRGB = new compareHexaRGB();
try {
BufferedImage img, img2;
File file = new File("eye1.jpg");
File file2 = new File("eye2.jpg");
image = new FileInputStream(file);
image2 = new FileInputStream(file2);
img = ImageIO.read(image);
img2 = ImageIO.read(image2);
int rowcol;
int width = img.getWidth();
int height = img.getHeight();
hexRGB.compareHexaRGB(width, height);
System.out.println("Image's Width: " + width);
System.out.println("Image's Height: " + height);
//hexRGB.check();
int[][] pixelData = new int[width * height][3];
System.out.println("Pixel Data: " + pixelData);
int[] rgb;
int count = 0;
img_hex2 = new String[width][height];
img_hex4 = new String[width][height];
for(int i=0; i<width; i++)
{
for(int j=0; j<height; j++)
{
rgb = newPD.getPixelData(img, i, j);
for(int k = 0; k < rgb.length; k++)
{
pixelData[count][k] = rgb[k];
//img_hex2[i][j] = newPD.getHexa2();
//img_hex4[i][j] = newPD.getHexa4();
}
img_hex2[width][height] = newPD.getHexa2();
img_hex4[width][height] = newPD.getHexa4();
System.out.println("Output: " + img_hex2[i][j]);
System.out.println("Output: " + img_hex4[i][j]);
count++;
System.out.println("\nRGB Counts: " + count);
}
}
int width2 = img2.getWidth();
int height2 = img2.getHeight();
System.out.println("Image's Width: " + width2);
System.out.println("Image's Height: " + height2);
int[][] pixelData2 = new int[width2 * height2][3];
System.out.println("Pixel Data: " + pixelData2);
int[] rgb2;
int counter = 0;
img_hex2 = new String[width2][height2];
img_hex4 = new String[width2][height2];
for(int i=0; i<width2; i++)
{
for(int j=0; j<height2; j++)
{
rgb2 = newPD.getPixelData(img2, i, j);
for(int k = 0; k < rgb2.length; k++)
{
pixelData2[counter][k] = rgb2[k];
}
img2_hex2[width2][height2] = newPD.getHexa2();
img2_hex4[width2][height2] = newPD.getHexa4();
counter++;
System.out.println("\nRGB2 Counts: " + counter);
}
}
}
catch (FileNotFoundException ex) {
Logger.getLogger(getPixelRGB1.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
try {
image.close();
}
catch (IOException ex) {
Logger.getLogger(getPixelRGB1.class.getName()).log(Level.SEVERE, null, ex);
}
}
hexRGB.check();
}
public String[][] display_imgHex2()
{
return img_hex2;
}
public String[][] display_imgHex4()
{
return img_hex4;
}
public String[][] display_img2Hex2()
{
return img2_hex2;
}
public String[][] display_img2Hex4()
{
return img2_hex4;
}
}
//Get Pixel RGB Process
public class getPixelData1
{
private static final double bitPerColor = 4.0;
private static int red;
private static int green;
private static int blue;
private static String hexa2;
private static String hexa4;
public static int[] getPixelData(BufferedImage img, int w, int h) throws IOException
{
int argb = img.getRGB(w, h);
int rgb[] = new int[]
{
(argb >> 16) & 0xff, //red
(argb >> 8) & 0xff, //green
(argb ) & 0xff //blue
};
red = rgb[0];
green = rgb[1]; //RGB Value in Decimal
blue = rgb[2];
System.out.println("\nRGBValue in Decimal --> " + "\nRed: " + red + " Green: " + green + " Blue: " + blue);
//Convert each channel RGB to Hexadecimal value
String rHex = Integer.toHexString((int)(red));
String gHex = Integer.toHexString((int)(green));
String bHex = Integer.toHexString((int)(blue));
System.out.println("\nRGBValue in Hexa --> " + "\nRed Green Blue " + rHex + gHex + bHex);
return rgb;
}
public String getHexa2()
{
//Check position 2 of hexa value for any changes
String hex = String.format("%02X%02X%02X", red, green, blue);
System.out.println("\nString RGB Hexa: " + hex);
hexa2 = hex.substring(1,2);
System.out.println("\nSubstring at position 2: " + hexa2);
return hexa2;
}
public String getHexa4()
{
//Check position 4 of hexa value for any changes
String hex = String.format("%02X%02X%02X", red, green, blue);
System.out.println("\nString RGB Hexa: " + hex);
hexa4 = hex.substring(3,4);
System.out.println("\nSubstring at position 4: " + hexa4);
return hexa4;
}
}
//Compare 2 images process
public class compareHexaRGB
{
private static int w;
private static int h;
public static void compareHexaRGB(int width, int height) throws IOException
{
w = width;
h = height;
}
public void check()
{
getPixelRGB1 newPD = new getPixelRGB1();
for(int i = 0; i < w; i++)
{
for(int j = 0; j < h; j++)
{
if(newPD.display_imgHex2().equals(newPD.display_img2Hex2()) && (newPD.display_imgHex4().equals(newPD.display_img2Hex4())))
{
System.out.println("Pixel values at position 2 and 4 are the same.");
}
else if(!newPD.display_imgHex2().equals(newPD.display_img2Hex2()) || (!newPD.display_imgHex4().equals(newPD.display_img2Hex4())))
{
System.out.println("Pixel values at position 2 are not the same.");
}
else if(!newPD.display_imgHex2().equals(newPD.display_img2Hex2()) || (!newPD.display_imgHex4().equals(newPD.display_img2Hex4())))
{
System.out.println("Pixel values at position 4 are not the same.");
}
}
}
}
}
Errors:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at getPixelRGB1.main(getPixelRGB1.java:79)
The change you have made is fundamentally incorrect. Please refer this updated class.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class getPixelRGB1 {
private static String[][] img_hex2;
private static String[][] img_hex4;
private static String[][] img2_hex2;
private static String[][] img2_hex4;
public static void main(String[] args) throws IOException {
FileInputStream image = null;
FileInputStream image2 = null;
getPixelData1 newPD = new getPixelData1();
compareHexaRGB hexRGB = new compareHexaRGB();
try {
BufferedImage img, img2;
File file = new File("eye1.jpg");
File file2 = new File("eye2.jpg");
image = new FileInputStream(file);
image2 = new FileInputStream(file2);
img = ImageIO.read(image);
img2 = ImageIO.read(image2);
int rowcol;
int width = img.getWidth();
int height = img.getHeight();
hexRGB.compareHexaRGB(width, height);
System.out.println("Image's Width: " + width);
System.out.println("Image's Height: " + height);
// hexRGB.check();
int[][] pixelData = new int[width * height][3];
System.out.println("Pixel Data: " + pixelData);
int[] rgb;
int count = 0;
img_hex2 = new String[width][height];
img_hex4 = new String[width][height];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
rgb = newPD.getPixelData(img, i, j);
for (int k = 0; k < rgb.length; k++) {
pixelData[count][k] = rgb[k];
// img_hex2[i][j] = newPD.getHexa2();
// img_hex4[i][j] = newPD.getHexa4();
}
img_hex2[i][j] = newPD.getHexa2(); // the code runs and
// stops here
img_hex4[i][j] = newPD.getHexa4();
System.out.println("Output: " + img_hex2[i][j]);
System.out.println("Output: " + img_hex4[i][j]);
count++;
System.out.println("\nRGB Counts: " + count);
}
}
int width2 = img2.getWidth();
int height2 = img2.getHeight();
System.out.println("Image's Width: " + width2);
System.out.println("Image's Height: " + height2);
int[][] pixelData2 = new int[width2 * height2][3];
System.out.println("Pixel Data: " + pixelData2);
int[] rgb2;
int counter = 0;
img2_hex2 = new String[width2][height2];
img2_hex4 = new String[width2][height2];
for (int i = 0; i < width2; i++) {
for (int j = 0; j < height2; j++) {
rgb2 = newPD.getPixelData(img2, i, j);
for (int k = 0; k < rgb2.length; k++) {
pixelData2[counter][k] = rgb2[k];
}
img2_hex2[i][j] = newPD.getHexa2();
img2_hex4[i][j] = newPD.getHexa4();
counter++;
System.out.println("\nRGB2 Counts: " + counter);
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(getPixelRGB1.class.getName()).log(Level.SEVERE,
null, ex);
} finally {
try {
image.close();
} catch (IOException ex) {
Logger.getLogger(getPixelRGB1.class.getName()).log(
Level.SEVERE, null, ex);
}
}
hexRGB.check();
}
public String[][] display_imgHex2() {
return img_hex2;
}
public String[][] display_imgHex4() {
return img_hex4;
}
public String[][] display_img2Hex2() {
return img2_hex2;
}
public String[][] display_img2Hex4() {
return img2_hex4;
}
}
One possible cause is the four uninitialized variables at the top.
private static String[][] img_hex2;
private static String[][] img_hex4;
private static String[][] img2_hex2;
private static String[][] img2_hex4;
The above four variables are accessed without allocating any memory.
A quick fix is to initialize them before the two for loops that use them.
img_hex2 = new String[width][height];
img_hex4 = new String[width][height];
for(int i=0; i<width; i++)
{
for(int j=0; j<height; j++)
{
.....
img2_hex2 = new String[width2][height2];
img2_hex4 = new String[width2][height2];;
for(int i=0; i<width2; i++)
{
for(int j=0; j<height2; j++
I am using eclipse to export my project as a runnable jar file, when I try to run it nothing happens, when I run it using cmd I get this error.
C:\Users\Enes\Desktop>cmd.exe
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\Enes\Desktop>java -jar Game.Jar
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoa
der.java:58)
Caused by: java.lang.NullPointerException
at scrolls.Resources.createArray(Resources.java:111)
at scrolls.Player.<init>(Player.java:31)
at scrolls.Draw.<init>(Draw.java:27)
at scrolls.Frame.main(Frame.java:18)
... 5 more
C:\Users\Enes\Desktop>
When I run it using eclipse it runs fine with no errors or warnings.
This is my Resource file which seems to be causing the problem at line 111
package scrolls;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.imgscalr.Scalr;
public class Resources
{
Map map;
static BufferedImage[] textures = new BufferedImage[8];
static BufferedImage[] mapTextures = new BufferedImage[9];
static BufferedImage texture;
static BufferedImage[] waterAnimated = new BufferedImage[64];
static BufferedImage water;
static BufferedImage icon;
public static Font f, fs;
static int imageCounter = 0;
public Resources()
{
map = new Map();
textures();
createArray(texture, textures, 32, 1, 8);
createArray(water, waterAnimated, 32, 64, 1);
getFont();
buildMapTextures(textures, mapTextures);
}
public static void counter()
{
imageCounter++;
if (imageCounter >= 500)
imageCounter = 0;
//System.out.println(imageCounter / 8);
}
private void buildMapTextures(BufferedImage[] textures, BufferedImage[] mapTextures)
{
for (int i = 0; i <= 7; i++)
{
mapTextures[i] = resize(textures[i], 3, 3);
}
mapTextures[8] = resize(waterAnimated[2], 3, 3);
}
private BufferedImage resize(BufferedImage image, int newW, int newH)
{
BufferedImage thumbnail = Scalr.resize(image, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_EXACT, newW, newH, Scalr.OP_ANTIALIAS);
return thumbnail;
}
public static BufferedImage waterAnimation()
{
return waterAnimated[imageCounter / 8];
}
private void textures()
{
try
{
texture = ImageIO.read(new File("src/resources/textures.png"));
} catch (IOException e)
{
}
try
{
water = ImageIO.read(new File("src/resources/water.png"));
} catch (IOException e)
{
}
try
{
icon = ImageIO.read(new File("src/resources/icon.png"));
} catch (IOException e)
{
}
}
static BufferedImage player()
{
BufferedImage player = null;
try
{
player = ImageIO.read(new File("src/resources/player.png"));
} catch (IOException e)
{
}
return player;
}
static void createArray(BufferedImage image, BufferedImage[] images, int size, int rows, int cols)
{
BufferedImage temp = image;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
images[(i * cols) + j] = temp.getSubimage(j * size, i * size, size, size); // line 111
}
}
}
public static void readLevel(String filename, int[][] level, int part)
{
try
{
File f = new File("src/resources/levels/" + part + "/" + filename + ".txt");
FileReader fr = new FileReader(f);
BufferedReader in = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
byte b = 0;
while ((b = (byte) in.read()) != -1)
{
sb.append("" + ((char) b));
}
String str = sb.toString();
String[] lines = str.split("(\n|\r)+");
for (int i = 0; i < lines.length; i++)
{
for (int j = 0; j < lines[i].length(); j++)
{
level[i][j] = Integer.parseInt("" + lines[i].charAt(j));
}
}
in.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
private static void getFont()
{
try
{
f = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream("src/resources/Jet Set.ttf"));
fs = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream("src/resources/Jet Set.ttf"));
} catch (Exception e)
{
System.out.println(e);
}
f = f.deriveFont(22f);
fs = fs.deriveFont(13f);
}
}
Player code
package scrolls;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Transparency;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
public class Player
{
static int x, y, dx, dy;
BufferedImage[] sprites = new BufferedImage[8];
int rotation = 0;
int imageCounter = 0;
public static boolean moving = false;
static int playerEnergy = 150000;
static int playerLvl = 1;
static int playerExp = 3;
static int expNeeded = (((playerLvl + 1) * playerLvl) * 2);
static int playerHealth = 100;
static int playerMana = 100;
static int mapRow = 6;
static int mapColumn = 8;
static int playerRow, playerColumn;
public Player()
{
y = 40;
x = 700;
Resources.createArray(Resources.player(), sprites, 66, 1, 8);
}
private void changeImage()
{
imageCounter++;
if (imageCounter >= 80)
imageCounter = 0;
}
public void move()
{
y = y + dy;
x = x + dx;
changeImage();
playerPosition();
}
static void mapPosition()
{
if (y < 0)
playerRow = 0;
else
playerRow = (y / 32) + 1;
if (x < 0)
playerColumn = 0;
else
playerColumn = (x / 32) + 1;
}
private void playerPosition()
{
if (x >= 817 - 59)
{
x = -24;
mapColumn++;
}
if (x <= -25)
{
x = 817 - 59;
mapColumn--;
}
if (y <= -25)
{
y = 599 - 152 - 41;
mapRow--;
}
if (y >= 599 - 152 - 40)
{
y = -24;
mapRow++;
}
}
public static int playerExp()
{
return playerExp;
}
public static int getNextExp()
{
return expNeeded;
}
public static int playerLvl()
{
if (playerExp >= expNeeded)
{
playerLvl++;
}
return playerLvl;
}
public static int playerHealth()
{
return playerHealth;
}
public static int playerMana()
{
return playerMana;
}
public static int playerEnergy()
{
if ((dx != 0) || (dy != 0))
playerEnergy--;
if ((dx != 0) && (dy != 0))
playerEnergy--;
return playerEnergy;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public static BufferedImage rotate(BufferedImage image, double angle)
{
double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
int w = image.getWidth(), h = image.getHeight();
int neww = (int) Math.floor(w * cos + h * sin), newh = (int) Math.floor(h * cos + w * sin);
GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
Graphics2D g = result.createGraphics();
g.translate((neww - w) / 2, (newh - h) / 2);
g.rotate(angle, w / 2, h / 2);
g.drawRenderedImage(image, null);
g.dispose();
return result;
}
public BufferedImage getPlayerImage()
{
roatePlayer();
int image = animatePlayer();
double angle = Math.toRadians(rotation);
if (dy != 0 || dx != 0)
{
return rotate(sprites[image], angle);
}
return rotate(sprites[0], angle);
}
private int animatePlayer()
{
return imageCounter / 10;
}
private void roatePlayer()
{
if (dy > 0)
rotation = 0;
if (dy < 0)
rotation = 180;
if (dx > 0)
rotation = -90;
if (dx < 0)
rotation = 90;
if (dy > 0 && dx > 0)
rotation = -45;
if (dy > 0 && dx < 0)
rotation = 45;
if (dy < 0 && dx < 0)
rotation = 135;
if (dy < 0 && dx > 0)
rotation = -135;
}
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if (key == KeyEvent.VK_A)
{
dx = -1;
rotation = -90;
}
if (key == KeyEvent.VK_S)
{
dy = 1;
rotation = 0;
}
if (key == KeyEvent.VK_D)
{
dx = 1;
rotation = 90;
}
if (key == KeyEvent.VK_W)
{
dy = -1;
rotation = 180;
}
}
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
if (key == KeyEvent.VK_A)
dx = 0;
if (key == KeyEvent.VK_S)
dy = 0;
if (key == KeyEvent.VK_D)
dx = 0;
if (key == KeyEvent.VK_W)
dy = 0;
}
}
I strongly suspect that you're loading some resources (sounds, images) either by assuming that they're present as files, or you're using appropriate getResource / getResourceAsStream calls, but your resources aren't present in the jar file. We can't really tell without seeing any of your code or what's in your jar file, but you should check where you're loading the resource, and why you expect the resource to be found.
Oh, and you may have a casing issue too - when it's loading resources from the Windows file system, asking for FOO.PNG will work even if the file is called foo.png; the same is not true when loading resources from a jar file.
Of course, you should look at Resources.java line 111 and Player.java line 31 to help pin down exactly what's going wrong (e.g. which resource is failing).
EDIT: Okay, now that we've got the code, it's exactly as I first suggested. This line of code in Resource.player():
player = ImageIO.read(new File("src/resources/player.png"));
... is loading player.png expecting it to be a file on the local file system. You want something like:
player = ImageIO.read(Resource.class.getResource("/src/resources/player.png"));
It's odd to have a src folder in your jar file, by the way. If you've actually just got the image in a reources directory, you'd want:
player = ImageIO.read(Resource.class.getResource("/resources/player.png"));