Image to 2D Array then getImage from it after process - java

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.

Related

how to tint a black and white .png image to a certain color in Java

I have a .png image that I need to tint a custom color with the RGB values of 207, 173, 23. (https://github.com/pret/pokecrystal/blob/master/gfx/tilesets/players_room.png?raw=true)
I did some research and found the following code:
public BufferedImage getBufferedImage(String source, int redPercent, int greenPercent, int bluePercent) throws IOException{
BufferedImage img = null;
File f = null;
try{
f = new File(source);
img = ImageIO.read(f);
}catch(IOException e){
System.out.println(e);
}
int width = img.getWidth();
int height = img.getHeight();
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
int p = img.getRGB(x,y);
int a = (p>>24)&0xff;
int r = (p>>16)&0xff;
int g = (p>>8)&0xff;
int b = p&0xff;
p = (a<<24) | (redPercent*r/100<<16) | (greenPercent*g/100<<8) | (bluePercent*b/100);
img.setRGB(x, y, p);
}
}
return img;
}
This method is supposed to return a buffered image with the entered RGB values. However, whenever I use it, it only returns a lighter of darker version of the image with no color. I am wondering if the problem lies in the image itself, perhaps having to do with the transparency, or is the problem the code?
The problem is that the PNG image is set up to hold greyscale data only and so the BufferedImage img is also only capable of holding greyscale data. To fix this just create an output BufferedImage in RGB colour mode.
I also tidied up your exception handling.
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
class SOQuestion {
public static BufferedImage getBufferedImage(String source,
int redPercent, int greenPercent, int bluePercent) {
BufferedImage img = null;
File f = null;
try {
f = new File(source);
img = ImageIO.read(f);
} catch (IOException e) {
System.out.println(e);
return null;
}
int width = img.getWidth();
int height = img.getHeight();
BufferedImage out = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int p = img.getRGB(x,y);
int a = (p>>24) & 0xff;
int r = (p>>16) & 0xff;
int g = (p>>8) & 0xff;
int b = p & 0xff;
p = (a<<24) | (redPercent*r/100<<16) |
(greenPercent*g/100<<8) | (bluePercent*b/100);
out.setRGB(x, y, p);
}
}
return out;
}
public static void main(String[] args) {
BufferedImage result = SOQuestion.getBufferedImage(args[0], 81, 68, 9);
File outputfile = new File("output.png");
try {
ImageIO.write(result, "png", outputfile);
} catch (IOException e) {
System.out.println(e);
}
}
}

Java not creating Image file (Using ImageIO)

I have been given an assignment where I have to read two images from secondary memory and I have to store them in two separate matrices. Then I have to multiply these matrices and convert the resultant matrix back to an image and store it in the HDD. Here is the code:
package ISI;
import java.io.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import javax.imageio.ImageIO;
import javax.swing.*;
class ImageMultiplication {
BufferedImage img1, img2;
File f1, f2;
int matrix1[][], matrix2[][], matrix3[][];
int w,h;
ImageMultiplication() {
img1 = img2 = null;
f1 = f2 = null;
w = 500;
h = 400;
}
void readImages() throws IOException {
f1 = new File("image1.jpg");
f2 = new File("image2.jpg");
img1 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
img2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
img1 = ImageIO.read(f1);
img2 = ImageIO.read(f2);
System.out.println("\nReading of images complete");
}
void convertToMatrix() {
int [] array1 = new int[w*h];
matrix1 = new int[h][w];
int [] array2 = new int[w*h];
matrix2 = new int[w][h];
matrix3 = new int[h][h];
try {
img1.getRGB(0, 0, w, h, array1, 0, w);
img2.getRGB(0, 0, w, h, array2, 0, w);
}
catch(Exception e) {
System.out.println("\nInterrupted");
}
int count=0;
for(int i=0;i<h;i++) {
for(int j=0;j<w;j++) {
if(count == array1.length)
break;
matrix1[i][j] = array1[count];
count++;
}
}
count=0;
for(int i=0;i<w;i++) {
for(int j=0;j<h;j++) {
if(count == array2.length)
break;
matrix2[i][j]=array2[count];
count++;
}
}
int sum = 0, c, d, k;
for (c = 0; c < h; c++) {
for (d = 0; d < h; d++) {
for (k = 0; k < w; k++)
sum = sum + matrix1[c][k] * matrix2[k][d];
matrix3[c][d] = sum;
sum = 0;
}
}
/* Comment snippet 1
for(int i = 0; i<h; i++) {
for(int j = 0; j<h; j++)
System.out.print(" "+matrix3[i][j]);
System.out.println();
}
*/
}
void convertMatrixToImage() {
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
try {
for(int i=0; i<h; i++) {
for(int j=0; j<h; j++) {
int a = matrix3[i][j];
Color newColor = new Color(a,a,a);
image.setRGB(j,i,newColor.getRGB());
}
}
ImageIO.write(image, "jpg", new File("Output.jpg"));
}
catch(Exception e) {}
System.out.println(image.toString());
System.out.println("\nThe output image has been generated!");
}
public static void main(String [] args) throws IOException {
ImageMultiplication i = new ImageMultiplication();
i.readImages();
i.convertToMatrix();
i.convertMatrixToImage();
}
}
The file executes with no problem.
See
The problem is, However, that no image file is created or written in the directory ( void convertMatrixToImage() ). If I uncomment (comment snippet 1), I get a 2D matrix as the output on the console window where each index shows a numeric value which I am assuming to be the pixed RGB value. But there is no sign whatsoever of any image file ever being created. Can somebody please help me out?
Note: I have tried converting the array to byte array and then writing the image file and I have tried other methods as well, but nothing seems to work. I tried it even on Windows but it also has the same problem. Nowhere is the Output.jpg being created/written.
When I run your, modified code to print the Exception, I get...
java.lang.IllegalArgumentException: Color parameter outside of expected range: Red Green Blue
at java.awt.Color.testColorValueRange(Color.java:310)
at java.awt.Color.<init>(Color.java:395)
at java.awt.Color.<init>(Color.java:369)
at javaapplication194.ImageMultiplication.convertMatrixToImage(JavaApplication194.java:102)
at javaapplication194.ImageMultiplication.main(JavaApplication194.java:118)
Now, I'll be honest, I had no idea what this "really" means, but I know it has something to do with "color"
So I had a look back over the conversation code...
try {
for (int i = 0; i < h; i++) {
for (int j = 0; j < h; j++) {
int a = matrix3[i][j];
Color newColor = new Color(a, a, a);
image.setRGB(j, i, newColor.getRGB());
}
}
ImageIO.write(image, "jpg", new File("Output.jpg"));
} catch (Exception e) {
e.printStackTrace();
}
And noted...
int a = matrix3[i][j];
Color newColor = new Color(a, a, a);
image.setRGB(j, i, newColor.getRGB());
This seems very weird to me for a number of reasons...
You use getRGB to get the color as a packed int value
You try and make a new color from this packed int
You use getRGB to return a packed int from a color based on a packed int
All of which seems, wrong and unnecessary, you already have a packed int RGB value, why not just use
int a = matrix3[i][j];
//Color newColor = new Color(a, a, a);
image.setRGB(j, i, a);
adding this, the error goes away and the image is created

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);

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.

Categories