I have the following method:
private void rotate_image(boolean right) {
if(image != null) {
if(right) {
this.degrees -= 0.005;
}
else {
this.degrees += 0.005;
}
AffineTransform transform = new AffineTransform();
transform.rotate(this.degrees, original_image.getWidth()/2, original_image.getHeight()/2);
AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BICUBIC);
this.image = op.filter(original_image, null);
}
}
The image is a Black and White one, meaning its pixels are either 0 or 255.
The "image" and "original_image" are BufferedImage types.
I wish to rotate it in small degrees until it reaches a certain position.
The rotation works fine, BUT... It fills my image with "noises" - pixels that aren't 0 or 255 and that were not present in the original image. So it loses some of its original characteristics.
As I will need later to analyze every pixel, I would very much appreciate if there is a method in Java that could rotate my image but keeps more of the original aspect.
These links to the 2 images show well what I mean. It's a pixel grid of a small part of the image before and after rotating:
Image Before: http://s13.postimg.org/3yvak746b/before1.png
Image After: http://s13.postimg.org/b0t86e7s3/after1.png
So, any ideas?
Thanks so much in advance!
Related
So, I recently asked a question on how to preload images in Java (preloading images in Java) and it worked great! Until I went to play the game. Framerate dropped drastically. I don't know what it was, but basically, I have a whole sprite map loaded into an array. Each image corresponds to a three-degree rotation. So, 5 degrees would become the 3-degree image, 6 would stay the 6, and so on (I tried Math.round and it actually made the 5 and 4-degree images go to the 6-degree image, and that's more desirable, however, it's slower)
I am looking for some ways to optimize the code. Here are my angle calculations:
private float getAngle(double x, double y) {
float angle = (float) Math.toDegrees(Math.atan2(y - this.getCenterY(), x - this.getCenterX()));
if(angle < 0){
angle += 360;
}
return angle;
}
The x and y values inputted into the method are the center x and y values of the enemy being targeted by the tower performing this calculation. Then this code is executed in the draw method:
if(airID==Value.towerCannon && (airRow>0 && airRow<5) && angle>=0) {
if(angle==Canvas.rotatedAirMap.length) angle = 0;
g.drawImage(Canvas.rotatedAirMap[angle][level-1], x, y, width, height, null);
} else {
g.drawImage(Canvas.airMap[airRow][airID], x, y, width, height, null);
}
}
This will draw the appropriate, preloaded image rotated at the specified angle (The "angle" - or image identifier - is calculated when the tower shoots by dividing the result of the angle calculation by three and then casting that to an int - I could also round that value)
Any suggestions on how to optimize this so I don't get such massive frame drops? I assume the frame drops are due to the VM heap size being too small, but I've increased it and still, nothing significant happens. Any help would be greatly appreciated.
Thanks!
#VGR here is what I did with your response:
public void paintComponent(Graphics g) {
if(isFirst) { //Define stuff when isFirst is true
define(); //Sets up the image arrays
GraphicsConfiguration config = getGraphicsConfiguration();
if(config == null) {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
config = env.getDefaultScreenDevice().getDefaultConfiguration();
}
BufferedImage compatibleImage = config.createCompatibleImage(image.getWidth(), image.getHeight(), image.getTransparency());
g = compatibleImage.createGraphics();
isFirst = false;
}
}
This works a little bit faster, but I had to do some workarounds. repaint() is called in the game loop (this class implements runnable) So the graphics component created by the repaint method (however that works) is the graphics I use for the whole game. Would this be the correct way to do it?
Translating images from their inherent color model to the color model of the current video mode can slow down rendering. To avoid this, you can make sure each image is compatible with the screen where your window resides:
BufferedImage image = ImageIO.read(/* ... */);
GraphicsConfiguration config = getGraphicsConfiguration();
if (config == null) {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment;
config = env.getDefaultScreenDevice().getDefaultConfiguration();
}
BufferedImage compatibleImage = config.createCompatibleImage(
image.getWidth(), image.getHeight(), image.getTransparency());
Graphics2D g = compatibleImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
image = compatibleImage;
If an image has the same color model as the current video mode, there is no translation needed when drawing it. It’s even possible that painting of such an image may be done entirely by the GPU.
So i have a lot of questions to this but first here is my assignment.
Write a method public Picture authenticate(Picture p) which checks to
see if ”this” picture and the picture p are identical. It returns a
new picture that it the same size as ”this” picture. For each pixel
position in the original picture ”this”, compare the color of that
pixel with the color of the pixel in the same position from second
picture. If the two pixels have the same color (i.e. the original is
not modified in the copy), set the color of this position in the
resulting picture to white. If the two pixels do not have the same
color, set the color of this position in the resulting picture to the
color of the pixel from the original picture. Return the resulting
picture. If the two pictures are not the same size, the resulting
picture should contain all black pixels
This is my code as of right now
public Picture Authenticate(Picture p)
{
Pixel sourcePixel = null;
Pixel targetPixel = null;
Picture result = new Picture(this.getWidth(), this.getHeight());
for(int sourceX = 0, targetX= getWidth()-1; sourceX < getWidth(); sourceX++,targetX++)
{
for(int sourceY = 0, targetY= getHeight(); sourceY< getHeight(); sourceY++,targetY++)
{
sourcePixel = this.getPixel(sourceX,sourceY);
targetPixel = result.getPixel(targetX, targetY);
}
if (sourcePixel.getColor() == targetPixel.getColor())
targetPixel.setColor(Color.WHITE);
else
targetPixel.setColor(Color.BLACK);
}
return result;
}
Here are my questions:
How do i make p in the authenticate parameter fit into this?
Am i going about this the right way within the loop?
With my if and else statement, i feel as if that is not even close
to changing the pixel i need tooa
How do i make p in the authenticate parameter fit into this?
this is your source image; p is the target image; result is where you place the output pixels resulting from comparing the source and target.
Am i going about this the right way within the loop?
Yes, but the if/else statement belongs inside the inner loop
With my if and else statement, i feel as if that is not even close to changing the pixel i need to
You are close. Keep working on it and step through the code in your debugger to see what is actually happening.
Don't get discouraged, this is closer than you think.
I'm trying to draw one image onto another using graphics.drawImage() but it's only working accurately for some images, others it messes up. My code's below, I've made sure texture is the right image when it enters the method so that's definitely not it. Any ideas?
private BufferedImage currentSheet;
public void swapRegionWithTexture(Rectangle region, Image texture) {
Graphics sheetGraphics = currentSheet.createGraphics();
for (int ix = region.x; ix < region.x + region.width; ix++) {
for (int iy = region.y; iy < region.y + region.height; iy++) {
currentSheet.setRGB(ix, iy, 0x000000);
}
}
sheetGraphics.drawImage(texture, region.x, region.y, null);
sheetGraphics.dispose();
}
The general idea is:
Grab the graphics to draw to.
Clear out the section of the graphics that will be drawn on.
Draw the image at the given location on the graphics.
Dispose of the graphics.
Your current atomic steps are thus:
create a new buffered image
write to that buffered image some crazy manipulation of the original texture (looks like you're reversing it?)
write the original image to the current sheet.
So what if you change this
sheetGraphics.drawImage(texture, region.x, region.y, null);
to this
sheetGraphics.drawImage(bufferedTexture, region.x, region.y, null);
Otherwise you're spending time reversing the image and putting into buffered texture and then never doing anything with that buffer... so chances are you intended to use that buffered texture somewhere.
Very simple thing I'm trying to do here. I would like to have 2 images on top of one another. When i use my mouse event dragged and clicked on the top image, the area of the top level image selected will fade and make the lower image visible.
The way I see it, there are 2 ways I can do this:
I can make the top image Transparent over time (within the selected area)
or
I can delete the pixels individually in a spray can style fashion. Think the spray can tool from MS paint back in the day.
Heres some very basic code that i started which just lays the images on top of eachother
PImage sand;
PImage fossil;
void setup()
{
size(400,400);
background(255,255,0);
frameRate(30);
fossil = loadImage("foss.jpg");
sand = loadImage("sand.jpeg");
}
void draw()
{
image(fossil, 0, 0, width,height);
image(sand, 0, 0, width,height);
smooth();
if (mousePressed) {
fill(0);
tint(255,127); //the opacity function
} else {
fill(255);
}
}
So has anyone any comments on these 2 ways of creating opacity or perhaps there an easier way I've overlooked?
Perhaps I wasn't clear in my Spec as the 2 comments below are asking for clarification.
In its simplest terms, I have 2 images on top of each other. I would like to be able to make some modification to the top level image which would make the bottom image visible. However I need to make this modification to only part of the top level image.
I would like to know which is the better option. To make part of the top image become transparent using tint() or to delete the pixels from the top layer.
Then I will proceed with that approach. Any indication as to how to do it is also appreciated.
I hope this clears up any confusion.
If you simply want to crossfade between images, it can be with tint() as you code suggest. You were in fact quite close:
PImage sand;
PImage fossil;
void setup()
{
size(400, 400);
fossil = loadImage("CellNoise.jpg");
sand = loadImage("CellVoronoi.jpg");
}
void draw()
{
//tint from 255 to 0 for the top image
tint(255,map(mouseX,0,width,255,0));
image(fossil, 0, 0, width, height);
//tint from 0 to 255 for the bottom image - 'cross fade'
tint(255,map(mouseX,0,width,0,255));
image(sand, 0, 0, width, height);
}
For the "spray can style " erosion you can simply copy pixels from a source image into the destination image. It's up to you how you loop through pixels (how many, what order, etc.) to get the "spray" like effect you want, but here's a basic example of how to use the copy() function:
PImage sand,fossil;
int side = 40;//size of square 'brush'
void setup()
{
size(400, 400);
fossil = loadImage("CellNoise.jpg");
sand = loadImage("CellVoronoi.jpg");
}
void draw()
{
image(fossil, 0, 0, 400, 400);
if(mousePressed) {
for(int y = 0 ; y < side ; y++){
for(int x = 0; x < side; x++){
//copy pixel from 'bottom' image to the top one
//map sketch dimensions to sand/fossil an dimensions to copy from/to right coords
int srcX = (int)map(mouseX+x,0,width+side,0,sand.width);
int srcY = (int)map(mouseY+y,0,height+side,0,sand.height);
int dstX = (int)map(mouseX+x,0,width+side,0,fossil.width);
int dstY = (int)map(mouseY+y,0,height+side,0,fossil.height);
fossil.set(dstX, dstY, sand.get(srcX,srcY));
}
}
}
}
Note what I am simply looping to copy a square (40x40 in my case), but you can find other fun ways to loop and get different effects.
Have fun!
So I've got this nice Android game (a snake-clone with animations), doing the final testing, when BAM! My second testing device (Nexus 1, HTC Magic was my 1.) flickers when drawing.
Does anyone know why this code won't work correctly with the Nexus 1?
public void draw(Canvas canv) {
int count = 0;
isHead = false;
for (int i = 0; i < SPACES; i++) {
if (mDrawSpaces[i]) {
count++;
if (count == SPACES - 1) {
setDrawSpacesToFalse();
if (bmp != null)
super.drawPlaceable(canv);
}
} else {
mDrawSpaces[i] = true;
return;
}
}
}
I have a list of Birds (Birds / UFOs / others) with SPACES (4) times as many elements which are being drawn on the screen. So I thought to myself, instead of calculating the rotation and scale of the pictures for every Bird, I merely have 3 placeholders between the Birds which each have a picture to be drawn once they're set to visible. These pictures are generated by the first Bird:
public void drawHead(Canvas canv) {
//calculate the rotation & mirroring of the picture
super.drawPlaceable(canv);
//generate the pics for smaller birds following it
mat.preScale((float) 0.6, (float) 0.6);
this.bmp = Bitmap.createBitmap(SPRITESHEET, Bird.mCurFrame
* BIG_W[mUseBird], 0, BIG_W[mUseBird], BIG_H[mUseBird],
mat, true);
}
Any ideas? Is my draw(Canvas) method wrong in some part?
EDIT: I don't know why, I don't know how, but this afternoon when I tested it again, it magically worked...
I can see you are using matrix to scale - another option would be to use
canvas.DrawBitmap(spriteSheet, fromRect, toRect, paint);
Where toRect should be a Rect class of any size, in this way you would create no bitmap objects when drawing game frames. The piant should have filter bitmap enabled.
To rotate you would have to use:
canvas.save();
canvas.rotate(spriteAngle,spriteCenterX, spriteCenterY);
canvas.DrawBitmap(spriteSheet, fromRect, toRect, paint);
canvas.restore();
This is a fast enough code for many 2D games, though not as fast and powerful as OpenGL.