What I need to do:
I trying to write some code for visualise every pixel of any character. I decided best way for it will be show pixels as rectangle in Tile Pane. So this is effect which i need to reach:
What's my problem:
I wrote some code to make it by take snaphost of text1 and save it as WritableImage. Then i use PixelReader for read each pixel of this image by argb method. In loop when each integer rgb value is greater than TRESHOLD (is brighter) I add new tile with white background. Unless I add tile with black background. But something is still wrong with my idea and I get this effect:
There is my code:
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
//Create single letter string
String letter = "a";
//Create new text
Text text1 = new Text(letter);
//Set font for text
text1.setFont(Font.font("Calibri", FontWeight.NORMAL, 12));
//Save text1 as writable image
WritableImage newImg = text1.snapshot(null, null);
//Take bounds of letter
int imgHeight = (int) newImg.getHeight();
int imgWidth = (int) newImg.getWidth();
//Create pixel reader from newImg
PixelReader reader = newImg.getPixelReader();
//This is for preview image
ImageView imgPreview = new ImageView(newImg);
//Create tilePane
TilePane tilePane = new TilePane();
//New group with tilePane inside
Group display = new Group(tilePane);
//Bg color
tilePane.setStyle("-fx-background-color: gray;");
//Small gaps between tiles
tilePane.setHgap(2);
tilePane.setVgap(2);
//Set quantity of columns equals image width
tilePane.setPrefColumns(imgWidth);
//Set quantity of rows equals image height
tilePane.setPrefRows(imgHeight );
//Here I set tolerance treshold
int TOLERANCE_THRESHOLD = 0xf0;
for (int x = 0; x < imgWidth; x++) {
for (int y = 0; y < imgHeight; y++) {
int argb = reader.getArgb(x, y);
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
int b = argb & 0xFF;
if (r >= TOLERANCE_THRESHOLD
&& g >= TOLERANCE_THRESHOLD
&& b >= TOLERANCE_THRESHOLD) {
tilePane.getChildren().add(createElement(Color.WHITE));
}
else tilePane.getChildren().add(createElement(Color.BLACK));
}
}
// Create new stage
Stage stage = new Stage();
//Create new group
Group grupa = new Group();
Scene scene = new Scene(grupa, 400, 300, Color.GRAY);
grupa.getChildren().addAll(display);
stage.setScene(scene);
stage.show();
}
private Rectangle createElement(Color color) {
Rectangle rectangle = new Rectangle(15, 15);
//rectangle.setStroke(Color.ORANGE);
rectangle.setFill(color);
return rectangle;
}
public static void main(String[] args) {
launch(args);
}
}
What I doing wrong? Maby are other ways to take this effect?
Your outer loop variable is the x-coordinate and the inner loop variable is the y-coordinate.
This means you read the pixels column by column left to right. TilePane however requires the children list to be ordered row by row from top to bottom.
To fix the issue simply swap the loops. Use:
for (int y = 0; y < imgHeight; y++) {
for (int x = 0; x < imgWidth; x++) {
...
}
}
Instead of
for (int x = 0; x < imgWidth; x++) {
for (int y = 0; y < imgHeight; y++) {
...
}
}
Related
I am attempting to create a new color palette for an image turned to gray scale, and then apply the palette to the gray scale image. I began the method that I wanted to use to apply the palette, but I ran into the error mentioned in the title. I used "java.awt.Color" already in my code, so I am not sure why I am getting the error. Also, as you will see, I placed a color inside the parenthesis.
/**
* This program takes an image, converts it to grayscale, and uses a color palette to create new colors for the image.
*
* #author Dylan Hubbs
* #version 08/02/16
*/
import java.awt.Color ;
class ColorPalette
{
public void grayscaleEffect(Picture pictureObj)
{
int redValue = 0; int greenValue = 0; int blueValue = 0;
Pixel grayscaleTargetPixel = new Pixel(pictureObj, 0,0);
Color grayscalePixelColor = null;
for(int y=0; y < pictureObj.getHeight(); y++)
{
for(int x = 0; x < pictureObj.getWidth(); x++)
{
grayscaleTargetPixel = pictureObj.getPixel(x,y);
grayscalePixelColor = grayscaleTargetPixel.getColor(); //gets the color of the target pixel
grayscalePixelColor = new Color((grayscaleTargetPixel.getRed() + grayscaleTargetPixel.getGreen() + grayscaleTargetPixel.getBlue()) / 3, (grayscaleTargetPixel.getRed() + grayscaleTargetPixel.getGreen() + grayscaleTargetPixel.getBlue()) / 3, (grayscaleTargetPixel.getRed() + grayscaleTargetPixel.getGreen() + grayscaleTargetPixel.getBlue()) / 3);
grayscaleTargetPixel.setColor(grayscalePixelColor); //sets the new color of the target pixel
}//end of the inner for loop
}//end of the outer for loop
pictureObj.explore(); //explore the Picture object which is now the altered image
pictureObj.write("grayscaleWashingtonMonument.jpg"); //write the altered Picture object to a new file
pictureObj.show();
}
public void paletteEffect(Picture pictureObj)
{
int redValue = 0; int greenValue = 0; int blueValue = 0;
Pixel paletteTargetPixel = new Pixel(pictureObj, 0,0);
Color palettePixelColor = null;
Color [] palette = {Color.RED, Color.BLUE, Color.CYAN, Color.GREEN, Color.YELLOW, Color.GRAY, Color.PINK, Color.ORANGE};
for(int y=0; y < pictureObj.getHeight(); y++)
{
for(int x = 0; x < pictureObj.getWidth(); x++)
{
paletteTargetPixel = pictureObj.getPixel(x,y);
palettePixelColor = paletteTargetPixel.getColor();
if(paletteTargetPixel.getRed() >= 1 && paletteTargetPixel.getRed() <= 31)
palettePixelColor.setColor(palette[0]);
else if(paletteTargetPixel.getRed() >= 32 && paletteTargetPixel.getRed() <= 62)
palettePixelColor.setColor(palette[1]);
else if(paletteTargetPixel.retRed() >= 63 && paletteTargetPixel.getRed() <=93)
palettePixelColor.setColor(palette[2]);
}
}
}
}
public class ColorPaletteTester
{
public static void main(String[] args)
{
Picture pictureObj = new Picture("washingtonmonument.jpg"); //creates a new Picture object representing the file in the parameter list
pictureObj.explore();
ColorPalette cp = new ColorPalette();
cp.grayscaleEffect(pictureObj);
cp.paletteEffect(pictureObj);
}
}
So, the error is coming at
palettePixelColor.setColor(palette[0]);
Does anyone know why this would be happening?
palettePixelColor is declared as java.awt.Color, which happens to be an immutable class with no setters. Depending on what Pixel is, it may have such a method.
You are probably trying to do something like
palettePixelColor = palette[0];
or
paletteTargetPixel.setColor(palette[0]);
i have an arraylist RecArray of objects with each object containing two int values, one for the width and for the height of a rectangle. Each rectangle's height and width are a multiple of ten. the rectangles have to be passed on to the surface as in the given order in RecArray from left to right and from top to bottom. my problem is i can not find the x,y coordinates of the next rectangle. what im trying to do is, starting at the coordinate (0,0) i generate the first rectangle, add it to an arraylist RecList. Then i set the x and y coordinates. x becomes x = x+RecArray.get(0).getLength1() + 1. if x is greater than the width of the jpanel surface then it becomes 0 and y becomes y = y + 10 . starting from the second object in the RecArray i try to generate rectangles with the given coordinates and width&height. Then i try to compare them with all the previous rectangles to see if there is any overlapping. if there is no overlapping, the rectangle will be drawn, if there is overlapping, the x coordinate of the rec becomes x = RecList.get(j).width+1 and if that exceeds the width x becomes 0 and y is y=y+10. Then i regenate the current rectangle with the new coordinates and compare with the other rectangles in RecList again till i find the right spot for the current rectangle.ive been dealing with that issue for the last 5 days and am really fed up now. i would greatly appreciate any tipps. and Please be patient with me. im still learning programming.
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle rec = new Rectangle(x, y, RecArray.get(0).getWidth(),
RecArray.get(0).getHeight());
RecList.add(rec);
recPaint(g2,RecArray.get(0));
x = x + RecArray.get(0).getWidth() + 1;
int i;
for (i = 1; i < RecArray.size(); i++) {
if (x >= this.getArea().getWidth()) {
x = 0;
y = y + 10;
}
Rectangle rec1 = new Rectangle(x, y, RecArray.get(i)
.getWidth(), RecArray.get(i).getheight());
for (int j= 0; j < RecList.size(); j++) {
if (!recIntersect(rec1, RecList.get(j))) {
RecList.add(rec1);
recPaint(g2,RecArray.get(i));
break;
}
else {
x = RecList.get(j).width;
if (x >= this.getFlaeche().getLength1()) {
x = 0;
y = y + 10;
}
rec1 = new Rectangle(x, y,RecArray.get(i). .getWidth(),
RecArray.get(i).getHeight());
}
x = x + RecArray.get(i).getWidth();
}
//With this method using the given rec parameter a rectangle will be drawn on the g2 and filled in blue colour
private void recPaint (Graphics2D g2, RecType rec){
g2.setColor(Color.BLUE);
g2.fillRect(x, y, rec.getWidth(),
rec.getLength2());
g2.setColor(Color.BLACK);
g2.drawRect(x, y, rec.getHeight(),
rec.getLength2());
}
// returns true, if two rectangles overlap
private boolean recIntersect(Rectangle rec1, Rectangle rec2) {
if( rec1.intersects(rec2)){
return true;
}
return false;
}
Edit: apparently i haven't stated clearly what my problem is. my problem is, that the way i generate (x,y) coordinates of the rectangles is obviously wrong. the way my algorithm works doesnt get the results i want. i want my rectangles to be placed neatly next to/above/below each other WITHOUT overlapping, which is not the case.
Separate out your List of Rectangles. Calculate the X, Y coordinates once.
Since I didn't have your object class, I used the Dimension class, which holds a width and a length. I used the Rectangle class to hold the objects that will eventually be drawn in your Swing GUI.
Divide and conquer. Separate out your GUI model, view, and controller(s). This way, you can focus on one piece of the puzzle at a time.
Here are the results of my test code when I ran it with a drawing area of 500, 400.
java.awt.Rectangle[x=0,y=0,width=100,height=100]
java.awt.Rectangle[x=100,y=0,width=20,height=10]
java.awt.Rectangle[x=120,y=0,width=40,height=20]
java.awt.Rectangle[x=160,y=0,width=60,height=40]
java.awt.Rectangle[x=220,y=0,width=80,height=60]
java.awt.Rectangle[x=300,y=0,width=20,height=10]
java.awt.Rectangle[x=320,y=0,width=120,height=110]
Here are the results of my test code when I ran it with a drawing area of 200, 200.
java.awt.Rectangle[x=0,y=0,width=100,height=100]
java.awt.Rectangle[x=100,y=0,width=20,height=10]
java.awt.Rectangle[x=120,y=0,width=40,height=20]
java.awt.Rectangle[x=0,y=100,width=60,height=40]
java.awt.Rectangle[x=60,y=100,width=80,height=60]
java.awt.Rectangle[x=140,y=100,width=20,height=10]
And here's the code. I fit rectangles on the X axis until I can't fit another rectangle. Then I add the maximum height to Y, reset the X to zero, reset the maximum height and fit the next row of rectangles.
Create test applications like I did here and make sure that you can create the GUI model long before you create the GUI view and GUI controller.
package com.ggl.testing;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
public class CalculatingRectangles {
public static void main(String[] args) {
CalculatingRectangles calculatingRectangles = new CalculatingRectangles();
Dimension drawingArea = new Dimension(200, 200);
List<Dimension> dimensions = new ArrayList<>();
dimensions.add(new Dimension(100, 100));
dimensions.add(new Dimension(20, 10));
dimensions.add(new Dimension(40, 20));
dimensions.add(new Dimension(60, 40));
dimensions.add(new Dimension(80, 60));
dimensions.add(new Dimension(20, 10));
dimensions.add(new Dimension(120, 110));
List<Rectangle> rectangles = calculatingRectangles
.calculatingRectangles(drawingArea, dimensions);
System.out.println(displayRectangles(rectangles));
}
private static String displayRectangles(List<Rectangle> rectangles) {
StringBuilder builder = new StringBuilder();
for (Rectangle r : rectangles) {
builder.append(r);
builder.append(System.getProperty("line.separator"));
}
return builder.toString();
}
public List<Rectangle> calculatingRectangles(Dimension drawingArea,
List<Dimension> dimensions) {
int width = drawingArea.width;
int height = drawingArea.height;
int x = 0;
int y = 0;
int index = 0;
int maxHeight = 0;
boolean hasRoom = dimensions.size() > index;
List<Rectangle> rectangles = new ArrayList<>();
while (hasRoom) {
Dimension d = dimensions.get(index);
maxHeight = Math.max(maxHeight, d.height);
if ((x + d.width) <= width && (y + maxHeight) <= height) {
Rectangle r = new Rectangle(x, y, d.width, d.height);
x += d.width;
rectangles.add(r);
index++;
if (index >= dimensions.size()) {
hasRoom = false;
}
} else {
y += maxHeight;
if (y > height) {
hasRoom = false;
}
x = 0;
}
}
return rectangles;
}
}
I am writing a program where I take one picture and replace the background of that picture.
The picture I have is:
And the background that I am using for the cat is:
I know that in order to this I have to use the cat picture and take the color pixels that are less than 255 because the red, green, and blue values for white are 255. So then I take those pixels that are less than 255, which make up the cat, and place it on the background picture in the same X and Y positions. The problem I am having is that I can not figure out how to code this to get it to work.
I have the basic code which is:
import java.awt.*;
public class TrueColors
{
public static void main(String [] args)
{
Picture pictureObj2 = new Picture("9.01 cat picture.jpg");
pictureObj2.explore();
int redValue = 0; int greenValue = 0; int blueValue = 0;
Pixel targetPixel = new Pixel(pictureObj2, 0, 0);
Color pixelColor = null;
for(int y = 0; y < pictureObj2.getHeight(); y++)
{
for(int x = 0; x < pictureObj2.getWidth(); x++)
{
targetPixel = pictureObj2.getPixel(x,y);
pixelColor = targetPixel.getColor();
redValue = pixelColor.getRed();
greenValue = pixelColor.getGreen();
blueValue = pixelColor.getBlue();
pixelColor = new Color(redValue, greenValue, blueValue);
targetPixel.setColor(pixelColor);
}
}
pictureObj2.explore();
pictureObj2.write("ColoredCat.jpg");
pictureObj2.show();
}
}
I was just wondering if you could help me figure out how to take the concept of this program that I understand and turn it into code
Thank you
What you have is almost correct. Simply read in your second picture like you have your first picture here:
Picture background = new Picture("background.png");
background.explore();
Then in your inner loop simply do:
targetPixel = pictureObj2.getPixel(x,y);
pixelColor = targetPixel.getColor();
if(!pixelColor.equals(WHITE)) //test if you have a blank pixel
background.getPixel(x,y).setColor(pixelColor); //if not its a cat pixel so add it on top of the background
I am working on a method in Java to do some simple edge detection. I want to take the difference of two color intensities one at a pixel and the other at the pixel directly below it. The picture that I am using is being colored black no matter what threshold I put in for the method. I am not sure if my current method is just not computing what I need it to but I am at a loss what i should be tracing to find the issue.
Here is my method thus far:
public void edgeDetection(double threshold)
{
Color white = new Color(1,1,1);
Color black = new Color(0,0,0);
Pixel topPixel = null;
Pixel lowerPixel = null;
double topIntensity;
double lowerIntensity;
for(int y = 0; y < this.getHeight()-1; y++){
for(int x = 0; x < this.getWidth(); x++){
topPixel = this.getPixel(x,y);
lowerPixel = this.getPixel(x,y+1);
topIntensity = (topPixel.getRed() + topPixel.getGreen() + topPixel.getBlue()) / 3;
lowerIntensity = (lowerPixel.getRed() + lowerPixel.getGreen() + lowerPixel.getBlue()) / 3;
if(Math.abs(topIntensity - lowerIntensity) < threshold)
topPixel.setColor(white);
else
topPixel.setColor(black);
}
}
}
new Color(1,1,1) calls the Color(int,int,int) constructor of Color which takes values between 0 and 255. So your Color white is still basically black (well, very dark grey, but not enough to notice).
If you want to use the Color(float,float,float) constructor, you need float literals:
Color white = new Color(1.0f,1.0f,1.0f);
public void edgeDetection(int edgeDist)
{
Pixel leftPixel = null;
Pixel rightPixel = null;
Pixel bottomPixel=null;
Pixel[][] pixels = this.getPixels2D();
Color rightColor = null;
boolean black;
for (int row = 0; row < pixels.length; row++)
{
for (int col = 0;
col < pixels[0].length; col++)
{
black=false;
leftPixel = pixels[row][col];
if (col<pixels[0].length-1)
{
rightPixel = pixels[row][col+1];
rightColor = rightPixel.getColor();
if (leftPixel.colorDistance(rightColor) >
edgeDist)
black=true;
}
if (row<pixels.length-1)
{
bottomPixel =pixels[row+1][col];
if (leftPixel.colorDistance(bottomPixel.getColor())>edgeDist)
black=true;
}
if (black)
leftPixel.setColor(Color.BLACK);
else
leftPixel.setColor(Color.WHITE);
}
}
}
I am working with a LayeredPane that contains two images, one on each layer. I have been working on a method that obtains the image positions (based on the label positions the images are in) and then save the bottom image (lower one from within the layeredPane) and also the top one if it is at all covering the bottom image (may only be a part of the image), however I have been having some trouble with this and I'm a bit unsure on how to get it working properly.
I have been stuck working on this for quite a while now so any help with my existing code or thoughts on how I should approach this another way would be a big help for me.
Thanks in advance.
public void saveImageLayering(BufferedImage topImg,BufferedImage bottomImg, JLabel topLabel, JLabel bottomLabel) {
int width = bottomImg.getWidth();
int height = bottomImg.getHeight();
Point bottomPoint = new Point();
Point topPoint = new Point();
bottomPoint = bottomLabel.getLocation();
topPoint = topLabel.getLocation();
System.out.println("image x coordinate " + bottomPoint.x);
System.out.println("image y coordinate " + bottomPoint.y);
//arrays to store the bottom image
int bottomRedImgArray[][] = new int[width][height];
int bottomGreenImgArray[][] = new int[width][height];
int bottomBlueImgArray[][] = new int[width][height];
//arrays to store the top image
int topRedImgArray[][] = new int[width][height];
int topGreenImgArray[][] = new int[width][height];
int topBlueImgArray[][] = new int[width][height];
//loop through the bottom image and get all pixels rgb values
for(int i = bottomPoint.x; i < width; i++){
for(int j = bottomPoint.y; j < height; j++){
//set pixel equal to the RGB value of the pixel being looked at
pixel = new Color(bottomImg.getRGB(i, j));
//contain the RGB values in the respective RGB arrays
bottomRedImgArray[i][j] = pixel.getRed();
bottomGreenImgArray[i][j] = pixel.getGreen();
bottomBlueImgArray[i][j] = pixel.getBlue();
}
}
//create new image the same size as old
BufferedImage newBottomImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//set values within the 2d array to the new image
for (int x1 = 0; x1 < width; x1++){
for (int y1 = 0; y1 < height; y1++){
//putting values back into buffered image
int newPixel = (int) bottomRedImgArray[x1][y1];
newPixel = (newPixel << 8) + (int) bottomGreenImgArray[x1][y1];
newPixel = (newPixel << 8) + (int) bottomBlueImgArray[x1][y1];
newBottomImage.setRGB(x1, y1, newPixel);
}
}
//create rectangle around bottom image to check if coordinates of top in inside and save only the ones that are
Rectangle rec = new Rectangle(bottomPoint.x, bottomPoint.y, bottomImg.getWidth(), bottomImg.getHeight());
//loop through the top image and get all pixels rgb values
for(int i = bottomPoint.x; i < bottomImg.getWidth(); i++){
for(int j = bottomPoint.y; j < bottomImg.getHeight(); j++){
//if top image is inside lower image then getRGB values
if (rec.contains(topPoint)) { //___________________________________________________________doesnt contain any..
if (firstPointFound == true) {
//set pixel equal to the RGB value of the pixel being looked at
pixel = new Color(topImg.getRGB(i, j));
//contain the RGB values in the respective RGB arrays
topRedImgArray[i][j] = pixel.getRed();
topGreenImgArray[i][j] = pixel.getGreen();
topBlueImgArray[i][j] = pixel.getBlue();
} else {
firstPoint = new Point(i, j);
firstPointFound = true;
}
}
}
}
//create new image the same size as old
BufferedImage newTopImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//set values within the 2d array to the new image
for (int x1 = 0; x1 < topImg.getWidth(); x1++){
for (int y1 = 0; y1 < topImg.getHeight(); y1++){
//putting values back into buffered image
int newPixel = (int) topRedImgArray[x1][y1];
newPixel = (newPixel << 8) + (int) topGreenImgArray[x1][y1];
newPixel = (newPixel << 8) + (int) topBlueImgArray[x1][y1];
newTopImage.setRGB(x1, y1, newPixel);
}
}
BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
//uses the Graphics.drawImage() to place them on top of each other
Graphics g = newImage.getGraphics();
g.drawImage(newBottomImage, bottomPoint.x, bottomPoint.y, null);
g.drawImage(newTopImage, firstPoint.x, firstPoint.y, null);
try {
//then save as image once all in correct order
File outputfile = new File("saved_Layered_Image.png");
ImageIO.write(newImage, "png", outputfile);
JOptionPane.showMessageDialog(null, "New image saved successfully");
} catch (IOException e) {
e.printStackTrace();
}
}
I'm not really sure why you're messing around with the pixels, however, the idea is relatively simple
Basically, you want to create a third "merged" image which is the same size as the bottomImage. From there, you simply want to paint the bottomImage onto the merged image at 0x0.
Then you need to calculate the distance that the topImage is away from bottomImage's location and paint it at that point.
BufferedImage merged = new BufferedImage(bottomImg.getWidth(), bottomImg.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = master.createGraphics();
g2d.drawImage(bottomImg, 0, 0, this);
int x = topPoint .x - bottomPoint .x;
int y = topPoint .y - bottomPoint .y;
g2d.drawImage(topImg, x, y, this);
g2d.dispose();
Using this basic idea, I was able to produce these...