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++
Related
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;
}
}
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;
}
}
Trying to correct a set of "out of order pixels", listed in a XML file previously parsed in Array (number of column on x assis, number of detectors failed) in TIF image using interpolation of (x-1) and (x+ number of failed detectors)/2.
In Input I have a Tif image, as single layer (PAN, MS1, MS2, MS3, MS4) and the Array. In output I want the new image corrected.
I'm having problems with setRGB in :
new_img.setRGB = ((row + numOfDetectors) + (row - 1)/ 2);
and IOException e, in :
} catch (IOException e) {
Sorry, I'm new in Java language. Thanks ..
class ArrayInterpolatorNew {
public static void main(String[] args) {
String path = "E:/IES_Interpol/Resources/Images/ByPass_PAN_C.tif";
String path1 = "E:/IES_Interpol/Resources/Images/ByPass_PAN_C_interpol.tif";
BufferedImage old_img = null;
try { old_img = ImageIO.read(new File(path));}
catch (Exception e) { e.printStackTrace(); }
// Developer may get all the pixels
int width = old_img.getWidth(null);
int height = old_img.getHeight(null);
BufferedImage new_img = new BufferedImage( old_img.getWidth(),
old_img.getHeight(),
BufferedImage.TYPE_BYTE_GRAY);
Graphics gr = new_img.getGraphics();
gr.drawImage(old_img, 0, 0, null);
gr.dispose();
try {
File file = new File("Resources/Images/ByPass_PAN_C_interpol.tif"); // The file to save to.
String format = "TIF"; // Example: "PNG" or "JPG"
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
ImageIO.write(new_img, "TIF", new File(path1));
//}
//catch (IOException e) { e.printStackTrace(); }
byte pix[] = new byte[1];
int n = new_img.getWidth();
int m = new_img.getHeight();
final int firstRow = 1;
final int numOfDetectors = 1;
//int row = image1.getWidth();
//int col = image1.getHeight();
double[][] matrix = new double[n][m];
double[][] Array = new double[firstRow][numOfDetectors];
//swips the rows
for (int row = 0; row < n; ++row)
{
//swips the columns
for (int col = 0; col < m; ++col)
{
//matrix[row][col] = new_img.getRGB(row, col);
new_img.getRaster().getDataElements(row, col, pix);
matrix[row][col] = pix[0];
}
for(int J = 0; J < firstRow; J++)
{
//if (row != J){
// set a pixel
//int image = image1.getRGB( row, col, pixelValue );
//image.setRGB(x, y, pixelValue);
if (row == J){
System.out.println("x,y: " + row + ", " + J + "num of Detectors: " + numOfDetectors);
new_img.setRGB = ((row + numOfDetectors) + (row - 1)/ 2);
if (row == J && numOfDetectors > 20){
System.out.println("x,y: " + row + ", " + J + "num of Detectors: " + numOfDetectors + "then > 20");
//new_img.setRGB(x, y, pixelValue);
int col = new_img.getHeight();
new_img.getRaster().getDataElements(row, col, pix);
matrix[row][col] = pix[0];
}
}
}
try {
//ImageIO.write(new_img, format, file);
} catch (IOException e) {
e.printStackTrace();
} finally { System.out.println("Images were written succesfully.");}
System.out.println("rest of the code...");
}
} finally {
}
}
}
When bigImg becomes an image it does show, but when sprites[dir] becomes an image it doesn't show.
When running, I drew a small box to show where the sprite will be and there is nothing inside it.
public void getSprite(){
BufferedImage bigImg = null;
try {
bigImg = ImageIO.read(new File("Pacman.png"));
} catch (IOException e) {
System.out.println("hey");
e.printStackTrace();
}
// The above line throws an checked IOException which must be caught.
final int width = 7;
final int height = 7;
final int rows = 4;
final int cols = 3;
BufferedImage[] sprites = new BufferedImage[rows * cols];
System.out.println(bigImg.getHeight() + "," + bigImg.getWidth());
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
sprites[(i * cols) + j] = bigImg.getSubimage(
j * width,
i * height,
width,
height
);
}
}
//image = bigImg;
}
public void setSprite (int direction){
System.out.println("HEY");
System.out.println(sprites[1].getHeight());
image = sprites[direction];
}
I'm a beginner to Java programming. I have the algorithm but I'm having trouble to code it. I would like to compare 2 similar images at position 2 and 4 of RGB hexadecimal pixel values to check whether one of the images has different pixel values than the other one.
My Algorithm logic:
if(image1.substring2 == image2.substring2) && (image1.substring4 == image2.substring4), pixels are the same.
if(image1.substring2 != image2.substring2) || (image1.substring4 != image2.substring4), pixels are not the same.
if(image1.substring2 != image2.substring2) && (image1.substring4 != image2.substring4), pixels are not the same.
I have the remaining codes here. I tried to separate all the process so it is easy for me to troubleshoot later.
//MAIN
public class getPixelRGB1
{
private static int a;
private static int r;
private static int g;
private static int b;
private static final double bitPerColor = 4.0;
public static void main(String[] args) throws IOException
{
FileInputStream image = null;
FileInputStream image2 = null;
getPixelData1 newPD = new getPixelData1();
try {
BufferedImage img, img2;
File file = new File("img0.jpg");
File file2 = new File("imgstega.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();
System.out.println("Image's Width: " + width);
System.out.println("Image's Height: " + height);
int[][] pixelData = new int[width * height][3];
System.out.println("Pixel Data: " + pixelData);
int[] rgb;
int count = 0;
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];
}
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];
int[] rgb2;
int counter = 0;
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];
}
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);
}
}
}
}
//1ST PROCESS - Get RGB Pixel Values
public class getPixelData1
{
private static final double bitPerColor = 4.0;
public 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
};
int red = rgb[0];
int green = rgb[1]; //RGB Value in Decimal
int 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);
//Check position 2 and 4 of hexa value for any changes
String hexa2, hexa4 = "";
String rgbHexa = rHex + gHex + bHex;
hexa2 = rgbHexa.substring(1,2);
System.out.println("\nString RGB Hexa: " + rgbHexa);
System.out.println("\nSubstring at position 2: " + hexa2);
String hex = String.format("%02X%02X%02X", red, green, blue);
hexa4 = hex.substring(3,4);
System.out.println("\nSubstring at position 4: " + hexa4);
return rgb;
}
}
//2nd Process - to compare the RGB Hex value of both images
public class compareHexaRGB
{
public int[] compareHexaRGB(BufferedImage img, BufferedImage img2, int w, int h) throws IOException
{
getPixelData1 newPD = new getPixelData1(); //get method from class getPixelData1 - is this correct?
if((img.hexa2.equals(img2.hexa2)) && (img.hexa4.equals(img2.hexa4)))
{
System.out.println("Pixel values at position 2 and 4 are the same.");
}
else if((img.hexa2 != img2.hexa2) || (img.hexa4 != img2.hexa4))
{
System.out.println("Pixel values at position 2 and 4 are not the same.");
}
else if((img.hexa2 != img2.hexa2) && (img.hexa4 != img2.hexa4))
{
System.out.println("Pixel values at position 2 and 4 are not the same.");
}
}
}
The error stated that the program cannot find symbol for hexa2 and hexa4 in bufferedImage. Can someone check whether I've done something wrong with my coding here? I'm still new to Java.
img is of type BufferedImage (javadoc). It does not contain any non-private (nor private) fields named hexa2 or hexa4.
What you need to do is to refactor your code to make sure you have access to them in compareHexaRGB(). There are probably many ways this can be done. Perhaps you could extend BufferedImage to include your fields, or perhaps you could just pass them as input to the method.
Which solution that would be the more elegant one is hard to determine given that we don't really have all your code (for example, I don't see compareHexaRGB() being called at all).
To be more precise about the compilation problem: By using img.hexa2 to access a field, you assume that there is a field called hexa2 in BufferedImage that is accessible from your class. This is true if a field for example is declared as public. More typically, the fields are private scoped and need to be accessed by a getter/setter. For BufferedImage, no such field exists at all.
Learn about access control here.