Rotating a BufferedImage and Saving it into a pixel array - java

I am trying to properly rotate a sword in my 2D game. I have a sword image file, and I wish to rotate the image at the player's location. I tried using Graphics2D and AffineTransform, but the problem is that the player moves on a different coordinate plane, the Screen class, and the Graphics uses the literal location of the pixels on the JFrame. So, I realized that I need to render the sword by rotating the image itself, and then saving it into a pixel array for my screen class to render. However, I don't know how to do this. Here is the code for my screen rendering method:
public void render(double d, double yOffset2, BufferedImage image, int colour,
int mirrorDir, double scale, SpriteSheet sheet) {
d -= xOffset;
yOffset2 -= yOffset;
boolean mirrorX = (mirrorDir & BIT_MIRROR_X) > 0;
boolean mirrorY = (mirrorDir & BIT_MIRROR_Y) > 0;
double scaleMap = scale - 1;
for (int y = 0; y < image.getHeight(); y++) {
int ySheet = y;
if (mirrorY)
ySheet = image.getHeight() - 1 - y;
int yPixel = (int) (y + yOffset2 + (y * scaleMap) - ((scaleMap * 8) / 2));
for (int x = 0; x < image.getWidth(); x++) {
int xPixel = (int) (x + d + (x * scaleMap) - ((scaleMap * 8) / 2));
int xSheet = x;
if (mirrorX)
xSheet = image.getWidth() - 1 - x;
int col = (colour >> (sheet.pixels[xSheet + ySheet
* sheet.width])) & 255;
if (col < 255) {
for (int yScale = 0; yScale < scale; yScale++) {
if (yPixel + yScale < 0 || yPixel + yScale >= height)
continue;
for (int xScale = 0; xScale < scale; xScale++) {
if (x + d < 0 || x + d >= width)
continue;
pixels[(xPixel + xScale) + (yPixel + yScale)
* width] = col;
}
}
}
}
}
}
Here is one of my poor attempts to call the render method from the Sword Class:
public void render(Screen screen) {
AffineTransform at = new AffineTransform();
at.rotate(1, image.getWidth() / 2, image.getHeight() / 2);
AffineTransformOp op = new AffineTransformOp(at,
AffineTransformOp.TYPE_BILINEAR);
image = op.filter(image, null);
screen.render(this.x, this.y, image, SwordColor, 1, 1.5, sheet);
hitBox.setLocation((int) this.x, (int) this.y);
for (Entity entity : level.getEntities()) {
if (entity instanceof Mob) {
if (hitBox.intersects(((Mob) entity).hitBox)) {
// ((Mob) entity).health--;
}
}
}
}
Thank you for any help you can provide, and please feel free to tell me if theres a better way to do this.

You can rotate() the image around an anchor point, also seen here in a Graphics2D context. The method concatenates translate(), rotate() and translate() operations, also seen here as explicit transformations.
Addendum: It rotates the image, but how do I save the pixels of the image as an array?
Once you filter() the image, use one of the ImageIO.write() methods to save the resulting RenderedImage, for example.

Related

LWJGL - Get part of image byte buffer

Hello I am fairly new to OpenGL and LWJGL
I have loaded an Image into a ByteBuffer using the STBImage binding in LWJGL. I can draw the image to the screen, this works perfectly fine.
Now I want to "slice" an image into multiple smaller images. I need it for my Tileset system
I only got it working to slice the image into the individual tiles.
But they are not correctly drawn. I think I know what the problem is, but I don't really get it to work how it should.
I think this is the problem:
int s = x * 4 + y * 4;
Here is the entire slicing function.
private void sliceTileset(Image[] images, float tileWidth, float tileHeight) {
// The pixelbuffer of the entire tileset image (Loaded via STBImage.stbi_load)
ByteBuffer tilesetPixelBuffer = tilesetImage.getPixelBuffer();
int xOffset = 0;
int yOffset = 0;
// Loop over all available tile slots ((tileSetWidth / tileWidth) +
// (tileSetHeight / tileHeight))
for (int i = 0; i < images.length; i++) {
ByteBuffer buffer = ByteBuffer.allocateDirect((int) (tileWidth * tileHeight * 4));
for (int y = 0; y < tileHeight; y++) {
for (int x = xOffset; x < tileWidth + xOffset; x++) {
int s = x * 4 + y * 4;
// get the pixel from the tileset image buffer
int r = tilesetPixelBuffer.get(s);
int g = tilesetPixelBuffer.get(s + 1);
int b = tilesetPixelBuffer.get(s + 2);
int a = tilesetPixelBuffer.get(s + 3);
// put it into the tile image buffer
buffer.put((byte) r);
buffer.put((byte) g);
buffer.put((byte) b);
buffer.put((byte) a);
}
}
// Create a new image with the tile image buffer
images[i] = new Image(buffer, tileWidth, tileHeight);
buffer.flip();
// Offset the x-position for the next tile
xOffset += tileWidth;
// Offset the y-position for the next tile
yOffset += tileHeight; // Currently does nothing
}
}
If your need more information just ask for it!

I try to rotat without lib but it make black points in picture

I am trying to rotate image without standard method , making color array and manipulate it, but when I invoke the, rotation I get black points (look the picture)
Here is my code, colScaled is the picture I am trying to convert to an array:
public void arrays() {
colScaled = zoom2();
int j = 0;
int i = 0;
angel = Integer.parseInt(this.mn.jTextField1.getText());
float degree = (float) Math.toRadians(angel);
float cos = (float) Math.cos(degree);
float sin = (float) Math.sin(degree);
int W = Math.round(colScaled[0].length * Math.abs(sin) + colScaled.length * Math.abs(cos));
int H = Math.round(colScaled[0].length * Math.abs(cos) + colScaled.length * Math.abs(sin));
int x;
int y;
int xn = (int) W / 2;
int yn = (int) H / 2;
int hw = (int) colScaled.length / 2;
int hh = (int) colScaled[0].length / 2;
BufferedImage image = new BufferedImage(W + 1, H + 1, im.getType());
for (i = 0; i < colScaled.length; i++) {
for (j = 0; j < colScaled[0].length; j++) {
x = Math.round((i - hw) * cos - (j - hh) * sin + xn);
y = Math.round((i - hw) * sin + (j - hh) * cos + yn);
image.setRGB(x, y, colScaled[i][j]);
}
}
ImageIcon ico = new ImageIcon(image);
this.mn.jLabel1.setIcon(ico);
}
Notice this block in your code :-
for (i = 0; i < colScaled.length; i++) {
for (j = 0; j < colScaled[0].length; j++) {
x = Math.round((i - hw) * cos - (j - hh) * sin + xn);
y = Math.round((i - hw) * sin + (j - hh) * cos + yn);
image.setRGB(x, y, colScaled[i][j]);
}
}
The x and y is pixel coordinate in source image (colScaled).
The objective of this code is to fill all pixels in destination image (image).
In your loop, there is no guarantee that all pixels in the destination image will be filled, even it is in the rectangle zone.
The above image depict the problem.
See? It is possible that the red pixel in the destination image will not be written.
The correct solution is to iterating pixel in destination image, then find a corresponding pixel in source image later.
Edit: After posting, I just saw the Spektre's comment.
I agree, it seems to be a duplicated question. The word "pixel array" made me thing it is not.

BufferedImage setRGB strange result

I've try to rotate an Image in Java using setRGB and BufferedImage, but I get a strange result. Has anyone any idea why?
BufferedImage pic1 = ImageIO.read(new File("Images/Input-1.bmp"));
int width = pic1.getWidth(null);
int height = pic1.getHeight(null);
double angle = Math.toRadians(90);
double sin = Math.sin(angle);
double cos = Math.cos(angle);
double x0 = 0.5 * (width - 1); // point to rotate about
double y0 = 0.5 * (height - 1); // center of image
BufferedImage pic2 = pic1;
// rotation
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
double a = x - x0;
double b = y - y0;
int xx = (int) (+a * cos - b * sin + x0);
int yy = (int) (+a * sin + b * cos + y0);
if (xx >= 0 && xx < width && yy >= 0 && yy < height) {
pic2.setRGB(x, y, pic1.getRGB(xx, yy));
}
}
}
ImageIO.write(pic2, "bmp", new File("Images/Output2.bmp"));
In the LEFT side is the original picture and in the RIGHT side it's my result. Have anyone any idea how can I fix it?
Thanks for help.
The problem is that you're using the same image as input and output:
BufferedImage pic2 = pic1;
You must create another image for pic2 and then do the rotation, copying pixels from Image1 to Image2.
Note, however, that using getRGB and setRGB it terribly slow. Its 100 times faster if you manipulate the pixels directly.

Color data is no being stored properly

I am attempting to make a rendering system with a depth map involved with the usual pixels for dealing with alpha. My problem is that no color is being set correctly! I have tried to debug using System.out.println and testing various components, but to no avail I have not found a solution.
The Variables
The variables that are involved with dealing with drawing, setting, and clearing of pixels are: private int[][] node, private int[] pixels, and private ArrayList<Integer> changedPixels.
private int[][] node deals with storing pixels and dealing with depth [depth][x + y * width] before transferring over to the BufferedImage pixels. The data is set to a clear black and the lowest depth it is a fully visible black.
private int[] pixels is the data from a BufferedImage to change it up, it is the only image every used! All data is by default fully visible black
private ArrayList<Integer> changedPixels deals with pixels that are there from the last frame so as to help boost FPS by not clearing the entire screen if not needed. Empty by default since not pixels were changed from a previous frame.
The Methods
I have several methods for the rendering system: setNode(int x, int y, int z, int color, int alpha, drawScreen(), and clearScreen(). I also have a drawing rectangle and sprite function which deals with adding pixels by calling the setNode() method to add in colors.
private void setNode(int x, int y, int z, int color, float alpha)
{
color = Pixel.getColor(alpha, color);
if (translate) // Move the pixel to the correct location
{
x -= transX;
y -= transY;
}
if (x < 0 || x >= width || y < 0 || y >= height || alpha <= 0.0f || nodeMap[z][x + y * width] == color) // Check if we need to draw the pixel
return;
for (int zz = z + 1; zz < maxDepth; zz++)
if (Pixel.getAlpha(nodeMap[zz][x + y * width]) >= 1)
return;
if (alpha < 1.0f) // If pixel isn't completely opaque, then set it's alpha to the given one
if (nodeMap[z][x + y * width] != color) // If color isn't equal to the one we supply, change it up correctly
color = Pixel.getColorBlend(color, nodeMap[z][x + y * width]);
if (color == Pixel.WHITE) System.out.println("Pixel is white at x: " + x + ", y: " + y);
nodeMap[z][x + y * width] = color;
}
public void drawScreen()
{
int color = clearColor;
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
{
for (int z = maxDepth - 1; z > 0; z--)
{
if (Pixel.getAlpha(nodeMap[z][x + y * width]) > 0f)
color = Pixel.getColorBlend(color, nodeMap[z][x + y * width]);
if (Pixel.getAlpha(color) >= 1f)
break;
}
if (pixels[x + y * width] != color)
{
pixels[x + y * width] = color;
changedPixels.add(x + y * width);
}
}
}
public void clearScreen()
{
for (Integer pixel : changedPixels)
{
for (int z = 0; z < maxDepth; z++)
{
if (z > 0)
nodeMap[z][pixel] = clearColor;
else
nodeMap[z][pixel] = bgColor;
}
}
changedPixels.clear();
}
public void drawRect(int offX, int offY, int z, int width, int height, int color)
{
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
setNode(x + offX, y + offY, z, color);
}
public static int getColorBlend(int color1, int color2)
{
float a1 = getAlpha(color1);
float a2 = getAlpha(color2);
float a = Math.max(a1, a2);
float r = ((getRed(color1) * a1) + (getRed(color2) * a2 * (1 - a1))) / a;
float g = ((getGreen(color1) * a1) + (getGreen(color2) * a2 * (1 - a1))) / a;
float b = ((getBlue(color1) * a1) + (getBlue(color2) * a2 * (1 - a1))) / a;
return Pixel.getColor(a, r, g, b);
}
The Test
What I do currently is initalize the rendering system and set the nodeMap and pixel map to the previously mentioned settings. After this has been completed a game engine begins and then a method in a gui button (you might need it), but it calls drawRect(0(x), 0(y), 1(z), 100(width), 20(height), Pixel.WHITE(color)) which works as I have testing to see if it's running the method and which pixels it's drawing to.
The Problem
The overall problem is that the screen is completely white, I can't quite figure out the reason! I do know it has nothing with the alpha blending, which works fine as I have used it will a previous version of a rendering system I did.
Any help is appreciate and sorry that this is quite a long question, I just wanted to make sure you had everything you may need help me solve this. I do realize this is not be very effiecent, but I still like the system. Thanks again!

Get average color on bufferedimage and bufferedimage portion as fast as possible

I am trying to find image in an image. I do this for desktop automation. At this moment, I'm trying to be fast, not precise. As such, I have decided to match similar image solely based on the same average color.
If I pick several icons on my desktop, for example:
And I will search for the last one (I'm still wondering what this file is):
You can clearly see what is most likely to be the match:
In different situations, this may not work. However when image size is given, it should be pretty reliable and lightning fast.
I can get a screenshot as BufferedImage object:
MSWindow window = MSWindow.windowFromName("Firefox", false);
BufferedImage img = window.screenshot();
//Or, if I can estimate smaller region for searching:
BufferedImage img2 = window.screenshotCrop(20,20,50,50);
Of course, the image to search image will be loaded from template saved in a file:
BufferedImage img = ImageIO.read(...whatever goes in there, I'm still confused...);
I explained what all I know so that we can focus on the only problem:
Q: How can I get average color on buffered image? How can I get such average color on sub-rectangle of that image?
Speed wins here. In this exceptional case, I consider it more valuable than code readability.
I think that no matter what you do, you are going to have an O(wh) operation, where w is your width and h is your height.
Therefore, I'm going to post this (naive) solution to fulfil the first part of your question as I do not believe there is a faster solution.
/*
* Where bi is your image, (x0,y0) is your upper left coordinate, and (w,h)
* are your width and height respectively
*/
public static Color averageColor(BufferedImage bi, int x0, int y0, int w,
int h) {
int x1 = x0 + w;
int y1 = y0 + h;
long sumr = 0, sumg = 0, sumb = 0;
for (int x = x0; x < x1; x++) {
for (int y = y0; y < y1; y++) {
Color pixel = new Color(bi.getRGB(x, y));
sumr += pixel.getRed();
sumg += pixel.getGreen();
sumb += pixel.getBlue();
}
}
int num = w * h;
return new Color(sumr / num, sumg / num, sumb / num);
}
There is a constant time method for finding the mean colour of a rectangular section of an image but it requires a linear preprocess. This should be fine in your case. This method can also be used to find the mean value of a rectangular prism in a 3d array or any higher dimensional analog of the problem. I will be using a gray scale example but this can be easily extended to 3 or more channels simply by repeating the process.
Lets say we have a 2 dimensional array of numbers we will call "img".
The first step is to generate a new array of the same dimensions where each element contains the sum of all values in the original image that lie within the rectangle that bounds that element and the top left element of the image.
You can use the following method to construct such an image in linear time:
int width = 1920;
int height = 1080;
//source data
int[] img = GrayScaleScreenCapture();
int[] helperImg = int[width * height]
for(int y = 0; y < height; ++y)
{
for(int x = 0; x < width; ++x)
{
int total = img[y * width + x];
if(x > 0)
{
//Add value from the pixel to the left in helperImg
total += helperImg[y * width + (x - 1)];
}
if(y > 0)
{
//Add value from the pixel above in helperImg
total += helperImg[(y - 1) * width + x];
}
if(x > 0 && y > 0)
{
//Subtract value from the pixel above and to the left in helperImg
total -= helperImg[(y - 1) * width + (x - 1)];
}
helperImg[y * width + x] = total;
}
}
Now we can use helperImg to find the total of all values within a given rectangle of img in constant time:
//Some Rectangle with corners (x0, y0), (x1, y0) , (x0, y1), (x1, y1)
int x0 = 50;
int x1 = 150;
int y0 = 25;
int y1 = 200;
int totalOfRect = helperImg[y1 * width + x1];
if(x0 > 0)
{
totalOfRect -= helperImg[y1 * width + (x0 - 1)];
}
if(y0 > 0)
{
totalOfRect -= helperImg[(y0 - 1) * width + x1];
}
if(x0 > 0 && y0 > 0)
{
totalOfRect += helperImg[(y0 - 1) * width + (x0 - 1)];
}
Finally, we simply divide totalOfRect by the area of the rectangle to get the mean value:
int rWidth = x1 - x0 + 1;
int rheight = y1 - y0 + 1;
int meanOfRect = totalOfRect / (rWidth * rHeight);
Here's a version based on k_g's answer for a full BufferedImage with adjustable sample precision (step).
public static Color getAverageColor(BufferedImage bi) {
int step = 5;
int sampled = 0;
long sumr = 0, sumg = 0, sumb = 0;
for (int x = 0; x < bi.getWidth(); x++) {
for (int y = 0; y < bi.getHeight(); y++) {
if (x % step == 0 && y % step == 0) {
Color pixel = new Color(bi.getRGB(x, y));
sumr += pixel.getRed();
sumg += pixel.getGreen();
sumb += pixel.getBlue();
sampled++;
}
}
}
int dim = bi.getWidth()*bi.getHeight();
// Log.info("step=" + step + " sampled " + sampled + " out of " + dim + " pixels (" + String.format("%.1f", (float)(100*sampled/dim)) + " %)");
return new Color(Math.round(sumr / sampled), Math.round(sumg / sampled), Math.round(sumb / sampled));
}

Categories

Resources