I am a new programmer.
Here, I am trying to import a library (com.digitalmodular).
What I want to do is run the java program in here
package demos;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Arrays;
import com.digitalmodular.utilities.RandomFunctions;
import com.digitalmodular.utilities.gui.ImageFunctions;
import com.digitalmodular.utilities.swing.window.PixelImage;
import com.digitalmodular.utilities.swing.window.PixelWindow;
/**
* #author jeronimus
*/
// Date 2014-02-28
public class AllColorDiffusion extends PixelWindow implements Runnable {
private static final int CHANNEL_BITS = 7;
public static void main(String[] args) {
int bits = CHANNEL_BITS * 3;
int heightBits = bits / 2;
int widthBits = bits - heightBits;
new AllColorDiffusion(CHANNEL_BITS, 1 << widthBits, 1 << heightBits);
}
private final int width;
private final int height;
private final int channelBits;
private final int channelSize;
private PixelImage img;
private javax.swing.Timer timer;
private boolean[] colorCube;
private long[] foundColors;
private boolean[] queued;
private int[] queue;
private int queuePointer = 0;
private int remaining;
public AllColorDiffusion(int channelBits, int width, int height) {
super(1024, 1024 * height / width);
RandomFunctions.RND.setSeed(0);
this.width = width;
this.height = height;
this.channelBits = channelBits;
channelSize = 1 << channelBits;
}
#Override
public void initialized() {
img = new PixelImage(width, height);
colorCube = new boolean[channelSize * channelSize * channelSize];
foundColors = new long[channelSize * channelSize * channelSize];
queued = new boolean[width * height];
queue = new int[width * height];
for (int i = 0; i < queue.length; i++)
queue[i] = i;
new Thread(this).start();
}
#Override
public void resized() {}
#Override
public void run() {
timer = new javax.swing.Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
draw();
}
});
while (true) {
img.clear(0);
init();
render();
}
// System.exit(0);
}
private void init() {
RandomFunctions.RND.setSeed(0);
Arrays.fill(colorCube, false);
Arrays.fill(queued, false);
remaining = width * height;
// Initial seeds (need to be the darkest colors, because of the darkest
// neighbor color search algorithm.)
setPixel(width / 2 + height / 2 * width, 0);
remaining--;
}
private void render() {
timer.start();
for (; remaining > 0; remaining--) {
int point = findPoint();
int color = findColor(point);
setPixel(point, color);
}
timer.stop();
draw();
try {
ImageFunctions.savePNG(System.currentTimeMillis() + ".png", img.image);
}
catch (IOException e1) {
e1.printStackTrace();
}
}
void draw() {
g.drawImage(img.image, 0, 0, getWidth(), getHeight(), 0, 0, width, height, null);
repaintNow();
}
private int findPoint() {
while (true) {
// Time to reshuffle?
if (queuePointer == 0) {
for (int i = queue.length - 1; i > 0; i--) {
int j = RandomFunctions.RND.nextInt(i);
int temp = queue[i];
queue[i] = queue[j];
queue[j] = temp;
queuePointer = queue.length;
}
}
if (queued[queue[--queuePointer]])
return queue[queuePointer];
}
}
private int findColor(int point) {
int x = point & width - 1;
int y = point / width;
// Calculate the reference color as the average of all 8-connected
// colors.
int r = 0;
int g = 0;
int b = 0;
int n = 0;
for (int j = -1; j <= 1; j++) {
for (int i = -1; i <= 1; i++) {
point = (x + i & width - 1) + width * (y + j & height - 1);
if (img.pixels[point] != 0) {
int pixel = img.pixels[point];
r += pixel >> 24 - channelBits & channelSize - 1;
g += pixel >> 16 - channelBits & channelSize - 1;
b += pixel >> 8 - channelBits & channelSize - 1;
n++;
}
}
}
r /= n;
g /= n;
b /= n;
// Find a color that is preferably darker but not too far from the
// original. This algorithm might fail to take some darker colors at the
// start, and when the image is almost done the size will become really
// huge because only bright reference pixels are being searched for.
// This happens with a probability of 50% with 6 channelBits, and more
// with higher channelBits values.
//
// Try incrementally larger distances from reference color.
for (int size = 2; size <= channelSize; size *= 2) {
n = 0;
// Find all colors in a neighborhood from the reference color (-1 if
// already taken).
for (int ri = r - size; ri <= r + size; ri++) {
if (ri < 0 || ri >= channelSize)
continue;
int plane = ri * channelSize * channelSize;
int dr = Math.abs(ri - r);
for (int gi = g - size; gi <= g + size; gi++) {
if (gi < 0 || gi >= channelSize)
continue;
int slice = plane + gi * channelSize;
int drg = Math.max(dr, Math.abs(gi - g));
int mrg = Math.min(ri, gi);
for (int bi = b - size; bi <= b + size; bi++) {
if (bi < 0 || bi >= channelSize)
continue;
if (Math.max(drg, Math.abs(bi - b)) > size)
continue;
if (!colorCube[slice + bi])
foundColors[n++] = Math.min(mrg, bi) << channelBits * 3 | slice + bi;
}
}
}
if (n > 0) {
// Sort by distance from origin.
Arrays.sort(foundColors, 0, n);
// Find a random color amongst all colors equally distant from
// the origin.
int lowest = (int)(foundColors[0] >> channelBits * 3);
for (int i = 1; i < n; i++) {
if (foundColors[i] >> channelBits * 3 > lowest) {
n = i;
break;
}
}
int nextInt = RandomFunctions.RND.nextInt(n);
return (int)(foundColors[nextInt] & (1 << channelBits * 3) - 1);
}
}
return -1;
}
private void setPixel(int point, int color) {
int b = color & channelSize - 1;
int g = color >> channelBits & channelSize - 1;
int r = color >> channelBits * 2 & channelSize - 1;
img.pixels[point] = 0xFF000000 | ((r << 8 | g) << 8 | b) << 8 - channelBits;
colorCube[color] = true;
int x = point & width - 1;
int y = point / width;
queued[point] = false;
for (int j = -1; j <= 1; j++) {
for (int i = -1; i <= 1; i++) {
point = (x + i & width - 1) + width * (y + j & height - 1);
if (img.pixels[point] == 0) {
queued[point] = true;
}
}
}
}
}
The thing is, I cant figure out how to import the library into IntelliJ. I have tried importing the library from Project Structure->Modules->Dependencies->Library->Java but failed. It appears that all the files in the given library are .java files, not .jar files
How should I import the library? Do I need to compile the whole library first? If yes, how?
This is my first question on this site, so my question may not be so clear :P
try
go to project settings -> Platform Settings -> SDKs -> Sourcepath (in the right panel) and add your downloaded zip -> Apply -> OK
Related
I implemented Gaussian Blur in Java, it seems to work on smaller radiuses but not on bigger ones. I'm not sure why on bigger radiuses the image darkens, I followed the same formula and the steps to apply the blur. Generating the blur matrix and applying it on the original image, and setting the pixel value to be the sum of the result of multiplying the image matrix with the blur matrix. I added the code I wrote below:
public class GaussianBlur extends ImageFilter {
private int radius;
private double sigma;
public GaussianBlur(String imageFilename, int radius) {
super(imageFilename);
this.radius = radius;
this.sigma = ((2.0 * radius) + 1.0) / 2.0;
}
#Override
public void applyFilter() throws IOException {
init();
Matrix<Double> gaussianMatrix = getGaussianMatrix();
Matrix<Color> imageMatrix, weightedImageMatrix;
Color weightedPixelSum;
for(int i = 0; i < getWidth(); i++) {
for(int j = 0; j < getHeight(); j++) {
imageMatrix = getImageMatrix(i, j);
weightedImageMatrix = multiplyImageMatrixWithWeight(imageMatrix, gaussianMatrix);
weightedPixelSum = getWeightedGaussianBlurValue(weightedImageMatrix);
getFilter().setRGB(i, j, weightedPixelSum.getRGB());
}
}
}
private Matrix<Double> getGaussianMatrix() {
Matrix<Double> gaussianMatrix = new Matrix<>(Double.class, radius);
double weightedSum = 0.0;
int matrixI = 0, matrixJ;
double gaussianValue;
for(int i = -radius; i <= radius; i++) {
matrixJ = 0;
for(int j = -radius; j <= radius; j++) {
gaussianValue = getGaussianValue(i, j);
weightedSum += gaussianValue;
gaussianMatrix.setValue(matrixI, matrixJ, gaussianValue);
matrixJ++;
}
matrixI++;
}
for(int i = 0; i < gaussianMatrix.getMatrix().length; i++) {
for(int j = 0; j < gaussianMatrix.getMatrix()[i].length; j++) {
gaussianMatrix.setValue(i, j, gaussianMatrix.getValue(i, j) / weightedSum);
}
}
return gaussianMatrix;
}
private double getGaussianValue(int x, int y) {
return 1.0 / (2.0 * Math.PI * sigma * sigma) * Math.pow(Math.E, -((x * x) + (y * y)) / (2.0 * (sigma * sigma)));
}
private Color getWeightedGaussianBlurValue(Matrix<Color> weightedImageMatrix) {
int r = 0, g = 0, b = 0;
for(int i = 0; i < weightedImageMatrix.getMatrix().length; i++) {
for(int j = 0; j < weightedImageMatrix.getMatrix()[i].length; j++) {
if(weightedImageMatrix.getValue(i, j) != null) {
r += weightedImageMatrix.getValue(i, j).getRed();
g += weightedImageMatrix.getValue(i, j).getGreen();
b += weightedImageMatrix.getValue(i, j).getBlue();
}
}
}
return new Color(r, g, b);
}
/*
* Multiply each image pixel with its matrix value to get a new matrix with the weighted pixel values.
*/
private Matrix<Color> multiplyImageMatrixWithWeight(Matrix<Color> imageMatrix, Matrix<Double> gaussianMatrix) {
Matrix<Color> weightedImageMatrix = new Matrix<>(Color.class, this.radius);
Color weightedValue;
for(int i = 0; i < weightedImageMatrix.getMatrix().length; i++) {
for(int j = 0; j < weightedImageMatrix.getMatrix()[i].length; j++) {
if(imageMatrix.getValue(i, j) != null) {
weightedValue = new Color(
(int) ((double) imageMatrix.getValue(i, j).getRed() * gaussianMatrix.getValue(i, j)),
(int) ((double) imageMatrix.getValue(i, j).getGreen() * gaussianMatrix.getValue(i, j)),
(int) ((double) imageMatrix.getValue(i, j).getBlue() * gaussianMatrix.getValue(i, j))
);
weightedImageMatrix.setValue(i, j, weightedValue);
} else {
weightedImageMatrix.setValue(i, j, null);
}
}
}
return weightedImageMatrix;
}
/*
* Given the center points (i, j), construct a matrix from the image to blur.
*/
private Matrix<Color> getImageMatrix(int i, int j) {
Matrix<Color> imageMatrix = new Matrix<>(Color.class, radius);
int matrixI = 0, matrixJ;
for(int x = i - radius; x <= i + radius; x++) {
matrixJ = 0;
for(int y = j - radius; y <= j + radius; y++) {
if(x > -1 && y > -1 && x < getOriginal().getWidth() && y < getOriginal().getHeight()) {
imageMatrix.setValue(matrixI, matrixJ, new Color(getOriginal().getRGB(x, y)));
} else {
imageMatrix.setValue(matrixI, matrixJ, null);
}
matrixJ++;
}
matrixI++;
}
return imageMatrix;
}
private class Color {
private int r, g, b;
public Color(int r, int g, int b) {
this.r = r;
this.g = g;
this.b = b;
}
public Color(int rgb) {
this((rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff);
}
public int getRed() {
return r;
}
public int getGreen() {
return g;
}
public int getBlue() {
return b;
}
public int getRGB() {
return (r << 16) | (g << 8) | b;
}
#Override
public String toString() {
return "(" + r + "," + g + "," + b + ")";
}
}
private class Matrix<T> {
private T[][] matrix;
public Matrix(Class<T> clazz, int radius) {
int length = (2 * radius) + 1;
matrix = (T[][]) Array.newInstance(clazz, length, length);
}
public T getValue(int i, int j) {
return matrix[i][j];
}
public void setValue(int i, int j, T value) {
matrix[i][j] = value;
}
public T[][] getMatrix() {
return matrix;
}
}
}
The class ImageFilter is just an abstract class with two instances of BufferedImage (one for the original image and one for the blurred image), and the displayImage function just displays the image in a message dialog.
The main method using this class is
public static void main(String[] args) throws IOException {
String filename = "res" + File.separator + "TajMahal.jpeg";
GaussianBlur gaussianBlur = new GaussianBlur(filename, 2);
gaussianBlur.applyFilter();
gaussianBlur.displayImage();
}
And below are the resulting images
The original image:
Blurred with radius 2:
Blurred with radius 7:
How come blurring it with radius 7 is darkening the image? Is there something missing in the formula or something that I have missed?
I want to divide the canvas into 8 vertical black and white Stripes. I wrote a method changeValue to change the value of the color everytime the loop is executed but the canvas is complete white. I think my changeValue method doesn't do as supposed but I can't explain why.
So far I got this:
public class Stripe {
public boolean switch = false;
private void stripes(int[] pixels, int width, int height) {
// TODO set some values here
int counter = 1;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pos = y * width + x;
int r, g, b;
// TODO code for the flag.
r = 255;
g = 255;
b = 255;
for (int i = 0; i < 8; i++) {
if (x < (counter * (width - 1)) / 8) {
r = changeValue();
g = changeValue();
b = changeValue();
}
counter++;
switch ^= true;
}
pixels[pos] = 0xFF000000 | (r << 16) | (g << 8) | b;
}
}
}
public int changeValue() {
if (switch) {
return 255;
} else {
return 0;
}
}
}
I am supposed not to write 8 If statements for the 8 stripes but this for example is the code for the Italian flag which are 3 vertical Stripes but which actually works:
private void flagItalian(int[] pixels, int width, int height) {
// TODO set some values here
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pos = y * width + x;
int r, g, b;
// TODO code for the flag.
r = 255;
g = 0;
b = 0;
if (x < 2 * (width - 1) / 3) {
r = 255;
g = 255;
b = 255;
}
if (x < (width - 1) / 3) {
r = 0;
g = 255;
b = 0;
}
pixels[pos] = 0xFF000000 | (r << 16) | (g << 8) | b;
}
}
}
If you need alternating color stripes then you could go for the classic odd/even checks. Instead of you below code block
for (int i = 0; i < 8; i++) {
if (x < (counter * (width - 1)) / 8) {
r = changeValue();
g = changeValue();
b = changeValue();
}
counter++;
switch ^= true;
}
Try replacing with this one
if (x%2) {
r = 255;
g = 255;
b = 255
} else {
r = 0;
g = 0;
b = 0;
}
I want to implement image processing in my project. I had used JLabs library. I want to do using this library following effects.
1) Deboss
2) Engrave
3) Satin etch
4) Custom shape like Cylinder.
This is sample image emboss code.
public class EmbossFilter
extends WholeImageFilter {
private static final float pixelScale = 255.9f;
private float azimuth = 2.3561945f;
private float elevation = 0.5235988f;
private boolean emboss = false;
private float width45 = 3.0f;
public void setAzimuth(float azimuth) {
this.azimuth = azimuth;
}
public float getAzimuth() {
return this.azimuth;
}
public void setElevation(float elevation) {
this.elevation = elevation;
}
public float getElevation() {
return this.elevation;
}
public void setBumpHeight(float bumpHeight) {
this.width45 = 3.0f * bumpHeight;
}
public float getBumpHeight() {
return this.width45 / 3.0f;
}
public void setEmboss(boolean emboss) {
this.emboss = emboss;
}
public boolean getEmboss() {
return this.emboss;
}
#Override
protected int[] filterPixels(int width, int height, int[] inPixels, Rect transformedSpace) {
int index = 0;
int[] outPixels = new int[width * height];
int bumpMapWidth = width;
int bumpMapHeight = height;
int[] bumpPixels = new int[bumpMapWidth * bumpMapHeight];
int i = 0;
while (i < inPixels.length) {
bumpPixels[i] = PixelUtils.brightness(inPixels[i]);
++i;
}
int Lx = (int) (Math.cos(this.azimuth) * Math.cos(this.elevation) * 255.89999389648438);
int Ly = (int) (Math.sin(this.azimuth) * Math.cos(this.elevation) * 255.89999389648438);
int Lz = (int) (Math.sin(this.elevation) * 255.89999389648438);
int Nz = (int) (1530.0f / this.width45);
int Nz2 = Nz * Nz;
int NzLz = Nz * Lz;
int background = Lz;
int bumpIndex = 0;
int y = 0;
while (y < height) {
int s1 = bumpIndex;
int s2 = s1 + bumpMapWidth;
int s3 = s2 + bumpMapWidth;
int x = 0;
while (x < width) {
int shade;
if (y != 0 && y < height - 2 && x != 0 && x < width - 2) {
int NdotL;
int Nx = bumpPixels[s1 - 1] + bumpPixels[s2 - 1] + bumpPixels[s3 - 1] - bumpPixels[s1 + 1] - bumpPixels[s2 + 1] - bumpPixels[s3 + 1];
int Ny = bumpPixels[s3 - 1] + bumpPixels[s3] + bumpPixels[s3 + 1] - bumpPixels[s1 - 1] - bumpPixels[s1] - bumpPixels[s1 + 1];
shade = Nx == 0 && Ny == 0 ? background : ((NdotL = Nx * Lx + Ny * Ly + NzLz) < 0 ? 0 : (int) ((double) NdotL / Math.sqrt(Nx * Nx + Ny * Ny + Nz2)));
} else {
shade = background;
}
if (this.emboss) {
int rgb = inPixels[index];
int a = rgb & -16777216;
int r = rgb >> 16 & 255;
int g = rgb >> 8 & 255;
int b = rgb & 255;
r = r * shade >> 8;
g = g * shade >> 8;
b = b * shade >> 8;
outPixels[index++] = a | r << 16 | g << 8 | b;
} else {
outPixels[index++] = -16777216 | shade << 16 | shade << 8 | shade;
}
++x;
++s1;
++s2;
++s3;
}
++y;
bumpIndex += bumpMapWidth;
}
return outPixels;
}
public String toString() {
return "Stylize/Emboss...";
}
}
How to achieve image effects using Jhlabs library or any other way please share with me.
I have a small game project where I have to use RMI to create a multiplayer game. I'm getting the following error:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalAccessError: tried to
access class PlayArea from class com.sun.proxy.$Proxy1
at com.sun.proxy.$Proxy1.getPlayArea(Unknown Source)
at GameClient.getPlayArea(GameClient.java:100)
at PlayBoard.paintComponent(GUI.java:264)
Now those references are as follows:
Part of GameClient.java
public PlayArea getPlayArea() {
PlayArea result = null;
try {
result = myServer.getPlayArea(clientID); // line 100 of GameClient.java
} catch (Exception e) {
System.out.println("Error: " + e);
System.exit(1);
}
return result;
}
And this is part of GUI.java
public void paintComponent(Graphics g) {
PlayArea playArea = gui.getGameEngine().getPlayArea(); // line 264 of GUI.java
super.paintComponent(g);
LinkedList bricks = new LinkedList();
int pixCoeff = brickSize - 1;
for (int y = 0; y < bricksPerSide; y++) {
int pixY = y * pixCoeff;
for (int x = 0; x < bricksPerSide; x++) {
int brick = playArea.getBrick(x, y);
if (Colour.isBase(brick))
continue;
if (gui.displayMode == GUI.NOMARKED && Colour.isMarked(brick)) {
continue;
}
int pixX = x * pixCoeff;
bricks.add(new BoardBrick(pixX, pixY,
gui.displayMode == GUI.MARKEDASORIGINAL ? ColourMapper
.map(Colour.original(brick)) : (Colour
.isMarked(brick) ? Color.WHITE : ColourMapper
.map(brick))));
}
}
g.setColor(ColourMapper.map(Colour.BASE));
g.fillRect(0, 0, (brickSize - 1) * bricksPerSide + 1, (brickSize - 1)
* bricksPerSide + 1);
while (bricks.size() > 0) {
BoardBrick brick = (BoardBrick) (bricks.removeFirst());
brick.drawBrick(g);
}
if (gui.getGameEngine().isGameOver())
gameOver(g);
}
And this is PlayArea.java
import java.util.Random;
class PlayArea implements java.io.Serializable {
public static final int NORTHSIDE = 0;
public static final int SOUTHSIDE = 1;
public static final int EASTSIDE = 2;
public static final int WESTSIDE = 3;
private int[][] grid;
public PlayArea(int size) {
grid = new int[size][size];
}
public static int randomSide(Random rng) {
return rng.nextInt(4);
}
public int getSize() {
return grid.length;
}
public int getBrick(int x, int y) {
return grid[x][y];
}
public int getBrick(Coord c) {
return getBrick(c.getX(), c.getY());
}
public void setBrick(int x, int y, int val) {
grid[x][y] = val;
}
public void setBrick(Coord c, int val) {
setBrick(c.getX(), c.getY(), val);
}
// --> play_area_init_collision_flipDraw
public void init() {
int size = getSize();
for (int x = 0; x < size; x++)
for (int y = 0; y < size; y++)
if (x == 0 || y == 0 || x == size - 1 || y == size - 1)
setBrick(x, y, Colour.WALL);
else
setBrick(x, y, Colour.BASE);
setBrick(size / 2, size / 2, Colour.WALL);
setBrick(size / 2 - 2, size / 2 - 2, Colour.WALL);
setBrick(size / 2 - 2, size / 2 + 2, Colour.WALL);
setBrick(size / 2 + 2, size / 2 - 2, Colour.WALL);
setBrick(size / 2 + 2, size / 2 + 2, Colour.WALL);
}
public boolean collision(PlayingBlock block) {
int topLeftX = block.getPosition().getX();
int topLeftY = block.getPosition().getY();
int height = block.getHeight();
int length = block.getLength();
for (int x = 0; x < length; x++)
for (int y = 0; y < height; y++)
if (!Colour.isBase(getBrick(topLeftX + x, topLeftY + y)))
return true;
return false;
}
public void flipDraw(PlayingBlock block) {
int topLeftX = block.getPosition().getX();
int topLeftY = block.getPosition().getY();
int height = block.getHeight();
int length = block.getLength();
for (int x = 0; x < length; x++)
for (int y = 0; y < height; y++)
setBrick(topLeftX + x, topLeftY + y, getBrick(topLeftX + x,
topLeftY + y)
^ block.getColour());
}
// --<
// --> play_area_getSquareColour_mark
public int getSquareColour(int topLeftX, int topLeftY, int size) {
// return 0 if no square found
// square colour otherwise
if (topLeftX + size > getSize() || topLeftY + size > getSize())
return 0;
int colour = getBrick(topLeftX, topLeftY);
if (!Colour.isPlayBrick(colour))
return 0;
for (int x = topLeftX; x < topLeftX + size; x++)
for (int y = topLeftY; y < topLeftY + size; y++)
if (!Colour.isSameColour(colour, getBrick(x, y)))
return 0;
return colour;
}
public void mark(int topLeftX, int topLeftY, int size) {
for (int x = topLeftX; x < topLeftX + size; x++)
for (int y = topLeftY; y < topLeftY + size; y++)
setBrick(x, y, Colour.mark(getBrick(x, y)));
}
// --<
}
Now, what's weird is, this runs in Windows using Java 1.6, but on OS X it doesn't and I don't have access to a Windows machine right now. I'm using 1.6.0_65 on OS X 10.9.
I have found many errors on the web regarding AWT-EventQueue-0 but most of them are NullPointerException errors, not IllegalAccessError. I would appreciate any help, I'm quite new to Java.
UPDATE: The code most definitely works in 1.5 and 1.6. This is most likely related to the included libraries. I will keep looking and edit this post accordingly.
Aloha,
i have trouble finding the error in my java code. In my opinion everything is fine and correct but the function is not executed correctly and I dont understand why. The function should detect the difference between the colors and calculate the arithmetic mean of them.
The resilt of it should be draw under the original picture. What did I miss, please help me?
package edge;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;
import javax.swing.JComponent;
import javax.swing.JFrame;
/**
*
* #author Alaska
*/
public class Edge extends JComponent {
final int W = 500;
final int H = 300;
Image m_TrgImg, m_SrcImg;
public Edge(JFrame father) {
try {
FileDialog diag = new FileDialog(father);
diag.setVisible(true);
m_SrcImg = getToolkit().getImage(diag.getDirectory() + diag.getFile()).getScaledInstance(W, H, Image.SCALE_SMOOTH);
MediaTracker mt = new MediaTracker(this);
mt.addImage(m_SrcImg, 0);
mt.waitForAll();
int[] srcPix = new int[W * H];
int[] trgPix = new int[W * H];
PixelGrabber grab = new PixelGrabber(m_SrcImg, 0, 0, W, H, srcPix, 0, W);
grab.getPixels();
MemoryImageSource imgProd = new MemoryImageSource(W, H, trgPix, 0, W);
m_TrgImg = createImage(imgProd);
detectEdges(srcPix, trgPix);
m_TrgImg.flush();
} catch (InterruptedException e) {
System.out.println(e);
}
}
#Override
public void paintComponent(Graphics g) {
g.drawImage(m_SrcImg, 0, 0, this);
g.drawImage(m_TrgImg, 0, H, this);
}
#Override
public Dimension getPreferredSize() {
return getMinimumSize();
}
#Override
public Dimension getMinimumSize() {
return new Dimension(W, H * 2);
}
private void detectEdges(int[] srcPix, int[] trgPix) {
for (int x = 0; x < W; ++x) {
for (int y = 0; y < H; ++y) {
trgPix[y * W + x] = compColor(srcPix, x, y);
}
}
}
private int getRed(int col) {
return (col >> 16) & 255;
}
private int getGreen(int col) {
return (col >> 8) & 255;
}
private int getBlue(int col) {
return col & 255;
}
private int compColor(int[] srcPix, int x, int y) {
int red = 0;
int green = 0;
int blue = 0;
int cnt = 0;
final int IDX = y * W + x;
final int RED = getRed(srcPix[IDX]);
final int GREEN = getGreen(srcPix[IDX]);
final int BLUE = getBlue(srcPix[IDX]);
for (int dx = -1; dx <= 1; ++dx) {
for (int dy = -1; dy <= 1; ++dy) {
if (dx != 0 || dy != 0) {
final int X = x + dx;
final int Y = y + dy;
final int LOCAL_IDX = Y * W + X;
if (0 <= X && X < W && 0 <= Y && Y < H) {
++cnt;
red += Math.abs(RED - getRed(srcPix[LOCAL_IDX]));
green += Math.abs(GREEN - getGreen(srcPix[LOCAL_IDX]));
blue += Math.abs(BLUE - getBlue(srcPix[LOCAL_IDX]));
}
}
}
}
return 0xff000000 | (255 - (red / cnt) << 16) | (255 - (green / cnt) << 8) | (255 - (blue / cnt));
}
public static void main(String[] args) throws Exception {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.getContentPane().add(new Edge(f));
f.pack();
f.setVisible(true);
}
}
You need to grab.grabPixels(), not grab.getPixels().
http://docs.oracle.com/javase/7/docs/api/java/awt/image/PixelGrabber.html
Also what trashgod said about Initial Threads. You need to create your GUI with SwingUtilities.invokeLater().
Edit
The method is executed correctly but you are getting all black values on the input because your pixel array contains only the initialized values which is 0.