Image won't show - java

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];
}

Related

Applying Mean filter on an image using java

When I give it a picture with salt and pepper noise it returns an image loosing all details and I don't know what's wrong with my code:
public class Q1 {
public static void main(String[] args) throws IOException {
BufferedImage img = ImageIO.read(new File("task1input.png"));
//get dimensions
int maxHeight = img.getHeight();
int maxWidth = img.getWidth();
//create 2D Array for new picture
int pictureFile[][] = new int [maxHeight][maxWidth];
for( int i = 0; i < maxHeight; i++ ){
for( int j = 0; j < maxWidth; j++ ){
pictureFile[i][j] = img.getRGB( j, i );
}
}
int output [][] = new int [maxHeight][maxWidth];
//Apply Mean Filter
for (int v=1; v<maxHeight; v++) {
for (int u=1; u<maxWidth; u++) {
//compute filter result for position (u,v)
int sum = 0;
for (int j=-1; j<=1; j++) {
for (int i=-1; i<=1; i++) {
if((u+(j)>=0 && v+(i)>=0 && u+(j)<maxWidth && v+(i)<maxHeight)){
int p = pictureFile[v+(i)][u+(j)];
sum = sum + p;
}
}
}
int q = (int) (sum /9);
output[v][u] = q;
}
}
//Turn the 2D array back into an image
BufferedImage theImage = new BufferedImage(
maxHeight,
maxWidth,
BufferedImage.TYPE_INT_RGB);
int value;
for(int y = 1; y<maxHeight; y++){
for(int x = 1; x<maxWidth; x++){
value = output[y][x] ;
theImage.setRGB(y, x, value);
}
}
File outputfile = new File("task1output3x3.png");
ImageIO.write(theImage, "png", outputfile);
}
}
getRGB "Returns an integer pixel in the default RGB color model (TYPE_INT_ARGB)" so therefore you have to extract the R, G, and B and add them separately; then put them back together. One way is this
int pixel=pictureFile[u+i][v+j];
int rr=(pixel&0x00ff0000)>>16, rg=(pixel&0x0000ff00)>>8, rb=pixel&0x000000ff;
sumr+=rr;
sumg+=rg;
sumb+=rb;
then to put them back together
sumr/=9; sumg/=9; sumb/=9;
newPixel=0xff000000|(sumr<<16)|(sumg<<8)|sumb);

Image to 2D Array then getImage from it after process

I am learn Image Processing Techniques and have some homework.
In my homework, which asked me to cover a RBG to gray image.
I've converted the images into 2D matrix, do somethings, and when i cover again from 2D matrix to image, some wrong happen.
This my code:
private static SampleModel samM;
public static int[][] imageToArrayPixel(File file) {
try {
BufferedImage img = ImageIO.read(file);
Raster raster = img.getData();
int w = raster.getWidth(), h = raster.getHeight();
int pixels[][] = new int[w][h];
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
pixels[x][y] = raster.getSample(x, y, 0);
System.out.print(" " + pixels[x][y]);
}
System.out.println("");
}
samM = raster.getSampleModel();
return pixels;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static java.awt.Image getImage(int pixels[][]) {
int w = pixels.length;
int h = pixels[0].length;
WritableRaster raster = Raster.createWritableRaster(samM, new Point(0, 0));
for (int i = 0; i < w; i++) {
for (int j = 0; j < pixels[i].length; j++) {
if (pixels[i][j] > 128) {
raster.setSample(i, j, 1, 255);
} else {
raster.setSample(i, j, 1, 0);
}
}
}
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
image.setData(raster);
File output = new File("check.jpg");
try {
ImageIO.write(image, "jpg", output);
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
public static java.awt.Image getImageWithRBG(Pixel pixels[][]) {
int w = pixels.length;
int h = pixels[0].length;
WritableRaster raster = Raster.createWritableRaster(samM, new Point(0, 0));
int[] pixelValue = new int[3];
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
pixelValue[0] = pixels[i][j].red;
pixelValue[1] = pixels[i][j].blue;
pixelValue[2] = pixels[i][j].green;
raster.setPixel(j, i, pixelValue);
}
}
BufferedImage image = new BufferedImage(h, w, BufferedImage.TYPE_CUSTOM);
image.setData(raster);
File output = new File("check.jpg");
try {
ImageIO.write(image, "jpg", output);
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
public static void main(String[] args) throws IOException {
int pixel[][] = imageToArrayPixel(new File("C:\\Users\\KimEricko\\Pictures\\1402373904964_500.jpg"));
getImage(pixel);
}
This my image which i use to covert:
before
and here is the photo that I received after restoration:
after
I don't understand why the picture after restoring contains only 1/3 of the original photograph.
What can I do to fix this?
looks to me like there is a bug in getImageWithRBG, that
raster.setPixel(j, i, pixelValue);
should be
raster.setPixel(i, j, pixelValue);
setPixel and setSample have similar inputs: x then y
I don't know if there are other problems, that is just the first thing I noticed.

Auto crop an image white border from all four side in Java

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!

Java - Why does ImageIO.read(filename) return null and the input image gets overwritten with 0 bytes?

I have several methods that manipulate a .jpg image: mirroring on x and y axis, tiling it, converting to ASCII text, and adjusting its brightness. All the methods work properly except the brightness one. When I run the brightness method, there is a NullPointerException in readGrayscaleImage() (see below - instructor written code). The BufferedImage is null, however it isn't when the method is called from any other of my methods (mirrors, tiling, ascii all read the file correctly). Not only is the BufferedImage null, the input image it is trying to read gets overwritten with 0 bytes and cannot be viewed in an image viewer, which would probably explain why the BufferedImage is null.
Here is a working method that calls readGrayscaleImage():
public static void tileImage(int h, int v, String infile, String outfile) {
int[][] result = readGrayscaleImage(infile);
int[][] tileResult = new int[result.length * h][result[0].length * v];
for (int hh = 0; hh < h; hh++) {
for (int vv = 0; vv < v; vv++) {
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
tileResult[i + hh * result.length][j + vv * result[i].length] = result[i][j];
}
}
}
}
writeGrayscaleImage(outfile, tileResult);
}
Here is the brightness method that results in the problem:
public static void adjustBrightness(int amount, String infile, String outfile) {
int[][] result = readGrayscaleImage(infile); // NullPointerException trace points here
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
if (result[i][j] + amount > 255)
result[i][j] = 255;
else if (result[i][j] + amount < 0)
result[i][j] = 0;
else
result[i][j] += amount;
}
}
writeGrayscaleImage(outfile, result);
}
Here is the instructor-written code that reads a greyscale .jpg file and returns an array of integers:
public static int[][] readGrayscaleImage(String filename) {
int [][] result = null; //create the array
try {
File imageFile = new File(filename); //create the file
BufferedImage image = ImageIO.read(imageFile);
int height = image.getHeight(); // NullPointerException POINTS HERE - image IS NULL
int width = image.getWidth();
result = new int[height][width]; //read each pixel value
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgb = image.getRGB(x, y);
result[y][x] = rgb & 0xff;
}
}
}
catch (Exception ioe) {
System.err.println("Problems reading file named " + filename);
ioe.printStackTrace();
System.exit(-1);
}
return result; //once we're done filling it, return the new array
}
Here is the instructor written method to write a .jpg:
public static void writeGrayscaleImage(String filename, int[][] array) {
int width = array[0].length;
int height = array.length;
try {
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB); //create the image
//set all its pixel values based on values in the input array
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgb = array[y][x];
rgb |= rgb << 8;
rgb |= rgb << 16;
image.setRGB(x, y, rgb);
}
}
//write the image to a file
File imageFile = new File(filename);
ImageIO.write(image, "jpg", imageFile);
}
catch (IOException ioe) {
System.err.println("Problems writing file named " + filename);
System.exit(-1);
}
}
(Wanted to comment but am not able to.)
BufferedImage image = ImageIO.read(filename);
Should this be
BufferedImage image = ImageIO.read(imageFile);
? I don't even see an override of read that takes a string.

Error occurred while analyze pixel values on two similar images

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++

Categories