I got the animation to work in my Snake Clone Game. But the problem based on the picture is that the images do not have transparency(notice the white background of the circle pictures. Programming-wise, is there a fix to be able to include transparency to these drawn images?
Here's a picture containing my code and the output of the program.
P.S. On a side note, I decided to paste the direct link instead of the IMG code because I cannot seem to get it to display on StackOverFlow. I put an exclamation point in the front of the IMG code but it did not work so here's the direct link.
As the other answer mentioned, the easiest way would probably be to simply use PNG images which have a transparent background (you can create these with an image editor like GIMP). Alternatively, if you are limited to PNG images with a solid background, here's an example of how to change a given color (e.g. white) in the PNG to transparent:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
public class SimpleFrame extends JFrame {
JPanel mainPanel = new JPanel() {
ImageIcon originalIcon = new ImageIcon("~/Pictures/apple.png");
ImageFilter filter = new RGBImageFilter() {
int transparentColor = Color.white.getRGB() | 0xFF000000;
public final int filterRGB(int x, int y, int rgb) {
if ((rgb | 0xFF000000) == transparentColor) {
return 0x00FFFFFF & rgb;
} else {
return rgb;
}
}
};
ImageProducer filteredImgProd = new FilteredImageSource(originalIcon.getImage().getSource(), filter);
Image transparentImg = Toolkit.getDefaultToolkit().createImage(filteredImgProd);
public void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getSize().width, getSize().height);
// draw the original icon
g.drawImage(originalIcon.getImage(), 100, 10, this);
// draw the transparent icon
g.drawImage(transparentImg, 140, 10, this);
}
};
public SimpleFrame() {
super("Transparency Example");
JPanel content = (JPanel)getContentPane();
mainPanel.setBackground(Color.black);
content.add("Center", mainPanel);
}
public static void main(String[] argv) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
SimpleFrame c = new SimpleFrame();
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.setSize(280,100);
c.setVisible(true);
}
});
}
}
Don't use paint to draw your images. Use some other program that uses alpha like Paint.net or Photoshop... If your going to use circles forever then you can use g.drawOval(x, y, w, h).
Simple use type to ARGB like this
BufferedImage image = new BufferedImage(
width, height,
BufferedImage.TYPE_INT_ARGB);
I hope it should work.
public BufferedImage makeTransparentImage(BufferedImage br) {
for (int i = 0; i < br.getHeight(); i++) {
for (int j = 0; j < br.getWidth(); j++) {
Color c = new Color(br.getRGB(j, i));
int r = c.getRed();
int b = c.getBlue();
int g = c.getGreen();
if ((r == 255 && b == 255 && g == 255)) {
System.out.println("r g b " + r + g + b);
br.setRGB(j, i, 0xFF000000);
}
}
}
return br;
}
If you draw a simple picture,
The easiest and fastest way I know...
Draw a picture in Macrosoft PowerPoint and click "Save as Picture" to get a transparent background. Next...
public class Node {
Image nodeImage[] = new Image[3];
public Node() {
try {
String address = "C:\\Users\\Desktop\\practice\\Simulation\\img\\";
nodeImage[0] = ImageIO.read(new File(address + "Node_noVehicle.png"));
nodeImage[1] = ImageIO.read(new File(address + "Node_setVehicle.png"));
nodeImage[2] = ImageIO.read(new File(address + "Node_inVehicle.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2dtemp = (Graphics2D) g.create();
g2dtemp.drawImage(Node.nodeImage[0],(int)x,(int)y,width,height,this);
}
}
Draw a picture in Macrosoft PowerPoint and click "Save as Picture" to get a transparent background.
Related
is it possible to display two pictures, next to each other with BufferedImage and Graphics2D ? or should I do it with other method ?
In my code below, I was able to display two images, but the picture 1 overlaps to the picture 2.
package zdjecie;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ObrazPanel extends JPanel {
private BufferedImage image;
private BufferedImage image2;
public ObrazPanel() {
super();
File imageFile = new File("C:\\Users\\KostrzewskiT\\eclipse-workspace\\zdjecie\\src\\zdjecie\\java.jpg");
File imageFile2 = new File("C:\\Users\\KostrzewskiT\\eclipse-workspace\\zdjecie\\src\\zdjecie\\java2.jpg");
try {
image = ImageIO.read(imageFile);
image2 = ImageIO.read(imageFile2);
} catch (IOException e) {
System.err.println("Blad odczytu obrazka");
e.printStackTrace();
}
Dimension dimension = new Dimension(image.getWidth(), image.getHeight());
setPreferredSize(dimension);
Dimension dimension2 = new Dimension(image2.getWidth(), image2.getHeight());
setPreferredSize(dimension2);
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(image, 0, 0, this);
g2d.drawImage(image2, 200, 200, this);
}
}
You call setPreferredSize twice, which results in the first call doing basically nothing. That means you always have a preferredSize equal to the dimensions of the second image. What you should do is to set the size to new Dimension(image.getWidth() + image2.getWidth(), image2.getHeight()) assuming both have the same height. If that is not the case set the height as the maximum of both images.
Secondly you need to offset the second image from the first image exactly by the width of the first image:
g2d.drawImage(image, 0, 0, this);
g2d.drawImage(image2, image.getWidth(), 0, this);
The logic of the math was incorrect. See the getPreferredSize() method for the correct way to calculate the required width, and the changes to the paintComponent(Graphics) method to place them side-by-side.
An alternative (not examined in this answer) is to put each image into a JLabel, then add the labels to a panel with an appropriate layout.
This is the effect of the changes:
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import java.net.*;
import javax.imageio.ImageIO;
public class ObrazPanel extends JPanel {
private BufferedImage image;
private BufferedImage image2;
public ObrazPanel() throws MalformedURLException {
super();
URL imageFile = new URL("https://i.stack.imgur.com/7bI1Y.jpg");
URL imageFile2 = new URL("https://i.stack.imgur.com/aH5zB.jpg");
try {
image = ImageIO.read(imageFile);
image2 = ImageIO.read(imageFile2);
} catch (Exception e) {
System.err.println("Blad odczytu obrazka");
e.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
int w = image.getWidth() + image2.getWidth();
int h1 = image.getHeight();
int h2 = image2.getHeight();
int h = h1>h2 ? h1 : h2;
return new Dimension(w,h);
}
#Override
public void paintComponent(Graphics g) {
// always best to start with this..
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(image, 0, 0, this);
g2d.drawImage(image2, image.getWidth(), 0, this);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ObrazPanel o;
try {
o = new ObrazPanel();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o);
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
};
SwingUtilities.invokeLater(r);
}
}
I would join the images whenever something changes and draw them to another buffered image. Then I can just redraw the combined image whenever the panel needs to be redrawn.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class SideBySideImagePanel extends JPanel {
private static final long serialVersionUID = 5868633578732134172L;
private BufferedImage left;
private BufferedImage right;
private BufferedImage join;
public SideBySideImagePanel() {
ClassLoader loader = this.getClass().getClassLoader();
BufferedImage left = null, right = null;
try {
left = ImageIO.read(loader.getResourceAsStream("resources/Android.png"));
right = ImageIO.read(loader.getResourceAsStream("resources/Java.png"));
} catch (IOException e) {
e.printStackTrace();
}
this.setLeft(left);
this.setRight(right);
}
public BufferedImage getLeft() {
return left;
}
public void setLeft(BufferedImage left) {
this.left = left;
}
public BufferedImage getRight() {
return right;
}
public void setRight(BufferedImage right) {
this.right = right;
}
#Override
public void invalidate() {
super.invalidate();
join = combineImages(left, right);
setPreferredSize(new Dimension(join.getWidth(), join.getHeight()));
}
#Override
public void paintComponent(Graphics g) {
g.drawImage(join, 0, 0, null);
}
private BufferedImage combineImages(BufferedImage left, BufferedImage right) {
int width = left.getWidth() + right.getWidth();
int height = Math.max(left.getHeight(), right.getHeight());
BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = combined.getGraphics();
g.drawImage(left, 0, 0, null);
g.drawImage(right, left.getWidth(), 0, null);
return combined;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Image Joiner");
SideBySideImagePanel panel = new SideBySideImagePanel();
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
});
}
}
I found some errors in your code and I did not got what are you trying to do...
1] Over there you are actually not using the first setup
Dimension dimension = new Dimension(image.getWidth(), image.getHeight());
setPreferredSize(dimension); //not used
Dimension dimension2 = new Dimension(image2.getWidth(), image2.getHeight());
setPreferredSize(dimension2); //because overridden by this
It means, panel is having dimensions same as the image2, you should to set it as follows:
height as max of the heights of both images
width at least as summarize of widths of both pictures (if you want to paint them in same panel, as you are trying)
2] what is the image and image2 datatypes? in the block above you have File but with different naming variables, File class ofcourse dont have width or height argument
I am assuming its Image due usage in Graphics.drawImage, then:
You need to setup preferred size as I mentioned:
height to max value of height from images
width at least as summarize value of each widths
Dimensions things:
Dimension panelDim = new Dimension(image.getWidth() + image2.getWidth(),Math.max(image.getHeight(),image2.getHeight()));
setPreferredSize(panelDim)
Then you can draw images in the original size
- due coordinates are having 0;0 in the left top corner and right bottom is this.getWidth(); this.getHeight()
- check eg. this explanation
- you need to start paint in the left bottom corner and then move to correct position increase "X" as the width of first image
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
/* public abstract boolean drawImage(Image img,
int x,
int y,
Color bgcolor,
ImageObserver observer)
*/
//start to paint at [0;0]
g2d.drawImage(image, 0, 0, this);
//start to paint just on the right side of first image (offset equals to width of first picture)- next pixel on the same line, on the bottom of the screen
g2d.drawImage(image2,image2.getWidth()+1, 0, this);
}
I didn't had a chance to test it, but it should be like this.
Important things are
you need to have proper dimensions for fitting both images
screen coordinates starts in the left top corner of the screens [0;0]
I have multiple images drawn with Graphics. How can I make them appear and disappear using a JCheckBox ?
private void drawImages(int index) {
Graphics g = mNew.getGraphics();
int x = index % this.width;
int y = index / this.width;
g.drawImage(imageLabelPixel.get(idImage-1), x, y, 100, 100, null);
}
You wouldn't use graphics to draw something on the screen you want to remove. Graphics just renders it on the screen along with all the other graphics you have drawn, It doesn't keep track of components
Your options are to add an action event to your checkbox and repaint the screen from scratch not drawing the image, or to just use a Label to draw the image and set it to invisible when the box is checked
I would do it like that:
JCheckBox cb = new JCheckBox();
ImgPanel p = new ImgPanel();
cb.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
if(cb.isSelected){
p.set(0);
} else {
p.set(-1);
}
}
});
.
public class ImgPanel extends JPanel {
private int i = 0;
private List<BufferedImage> imgs;
public ImgPanel(){
//init imgs
}
public void set(){
i = 0;
repaint();
}
#Override
public void paintComponent (Graphics g){
super.paintComponent(g);
if(i >= 0){
Image img = imgs.get(i-1);
Image img1 = img.getScaledInstance(100, 100, null);
}
g.drawImage(img1, 0, 0, null);
}
}
You can't simply draw on a graphic and then hand it to a compoennt or so (I don't really understand what your given code should have done). Instead you have to overwrite the paintComponent method of a Component and put your custom drawing code in there.
I am doing this for a project at school, in which much more functionality will be added later, but I am having trouble getting the basic setup done.
I tried doing this in C++ initially, but decided to switch to Java after reading some documentation on BufferedImage, but I am running into an issue with output. Essentially this is what I am designing the flow of the program to be:
1) Extract original image's (BMP image that is supplied in grayscale) grayscale values. 2) Create a currentImage variable to preserve the original image and perform the modifications to the image I intend to perform in the later stages of the project. 3) Create a reusable output method that will take the currentImage BufferedImage, and output it to a panel (and maybe a file as well.
Here is what I have so far, which currently results in nothing being outputted to the screen, and when I tried doing System logs, it is not setting the pixel values in my draw mechanism:
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
#SuppressWarnings("serial")
public class ImageDriver extends JFrame {
DrawPanel paintPanel;
static int width = 1024, height = 768;
BufferedImage originalImage, currentImage;
File theImageFile;
int[][] imageData;
public ImageDriver() {
super("Image Processing");
setSize(width, height);
setDefaultCloseOperation(EXIT_ON_CLOSE);
paintPanel = new DrawPanel(width, height);
add(paintPanel);
}
public void updateImageDisplay() {
System.out.println("In updateImageDisplay!");
paintPanel.setImage(currentImage);
}
public void readImage() {
try {
theImageFile = new File("images/img1.bmp");
originalImage = ImageIO.read(theImageFile);
currentImage = originalImage;
}
catch (IOException e) {
e.printStackTrace();
}
//get a raster to extract grayscale values
Raster image_raster = currentImage.getData();
//get pixel by pixel
int[] pixel = new int[1];
int[] buffer = new int[1];
imageData = new int[image_raster.getWidth()][image_raster.getHeight()];
for(int i = 0 ; i < image_raster.getWidth() ; i++)
for(int j = 0 ; j < image_raster.getHeight() ; j++) {
pixel = image_raster.getPixel(i, j, buffer);
imageData[i][j] = pixel[0];
//System.out.println("Pixel at: " + i + " x " + j + ": " + imageData[i][j]);
}
}
public void increaseContrast() {
}
public static void main(String[] args) {
ImageDriver driver = new ImageDriver();
driver.setVisible(true);
driver.readImage();
driver.updateImageDisplay();
driver.increaseContrast();
driver.updateImageDisplay();
}
class DrawPanel extends JPanel {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
public DrawPanel(int width, int height) {
setPreferredSize(new Dimension(width, height));
}
public void setImage(BufferedImage image) {
System.out.println("In setImage!");
this.image = image;
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("in paintPanel component!");
g = image.getGraphics();
g.drawImage(image, 0, 0, null);
}
}
}
I have a hunch that it is because I am declaring image in my DrawPanel to be an empty image at first, and setImage is not properly copying over all of its contents upon assignment. I tried fiddling around with using this:
this.image.setData(image.getData());
but to no avail.
I missing something here? Or is a complete re-write if the mechanism in order?
Thank you for reading.
The first thing that jumps out at me is this (in your paintComponent method)...
g = image.getGraphics();
g.drawImage(image, 0, 0, null);
Basically, you are painting the image back to itself, instead you should do something like like...
g.drawImage(image, 0, 0, this);
Using the Graphics context you were passed
i'm trying to write a jigsaw puzzle application where an image is cut in pieces, scrambled, and the user have to rearrange them with drag&drop to reassemble the original image. (something like this: http://www.jigzone.com/puzzles/74055D549FF0?z=5).
i have to write this in java with Graphics2d.
so, at first i'm trying to make some kind of component which can show a part of the image (a rectangle for now), and can be dragged with mouse.
the code below works well when there is only one one such component. the problem is, when i add the second component, the first one is no longer visible.
i'm really stuck here. i have a feeling i'm missing something really basic. or maybe i'm on a wrong way. any help will be greatly appreciated.
edit: i changed a bit the code according to suggestions, however, still not working as expected.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
public class GraphicDragAndDrop extends JPanel {
Rectangle rect;
Image img;
public GraphicDragAndDrop(String imgFile, int x0, int y0){
rect = new Rectangle(x0, y0, 150, 75);
img = new ImageIcon(imgFile).getImage();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setClip(rect);
int x = rect.x;
int y = rect.y;
g2d.drawImage(img, x, y, this);
}
public void setRect(int x, int y) {
rect.setLocation(x, y);
repaint();
}
public static void main(String[] args) {
// first piece
GraphicDragAndDrop piece1 = new GraphicDragAndDrop("a.png", 0, 0);
piece1.setRect(0, 0);
new GraphicDragController(piece1);
// second piece --> only this will be visible
GraphicDragAndDrop piece2 = new GraphicDragAndDrop("a.png", 200, 200);
//GraphicDragAndDrop piece2 = new GraphicDragAndDrop("b.png", 200, 200); // does'n work either
piece2.setRect(150, 150);
new GraphicDragController(piece2);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(piece1);
f.add(piece2);
f.setSize(500,500);
f.setLocation(300,100);
f.setVisible(true);
}
}
class GraphicDragController extends MouseInputAdapter {
GraphicDragAndDrop component;
Point offset = new Point();
boolean dragging = false;
public GraphicDragController(GraphicDragAndDrop gdad) {
component = gdad;
component.addMouseListener(this);
component.addMouseMotionListener(this);
}
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
Rectangle r = component.rect;
if(r.contains(p)) {
offset.x = p.x - r.x;
offset.y = p.y - r.y;
dragging = true;
}
}
public void mouseReleased(MouseEvent e) {
dragging = false;
}
public void mouseDragged(MouseEvent e) {
if(dragging) {
int x = e.getX() - offset.x;
int y = e.getY() - offset.y;
component.setRect(x, y);
}
}
}
Your code above is written to draw only one image:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setClip(rect);
int x = rect.x;
int y = rect.y;
// here
g2d.drawImage(new ImageIcon("a.png").getImage(), x, y, this);
}
If you need to draw more than one image, then consider creating a collection of images and iterating through the collection in paintComponent using a for loop:
also, never read in the image from within paintComponent since this method should be lean, mean and fast, and should concern itself with painting only. Also, there's no need to read the image in each time your program has to draw it as that's very inefficient and will slow the program unnecessarily. Instead read the image in once in the constructor or a similar init method.
For example,
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (Image img: myImageCollection) {
g2d.drawImage(img, 0, 0, this);
}
}
Edit
You state:
also, my plan was to have more objects of GraphicDragAndDrop class, each of them showing a different piece of the original image. is my approach wrong?
You could use components, but I have a feeling that it would be easy to drag images. I think it would be easier to rotate them for instance if you want your program to have this functionality. If not, though then sure use a component, but if you go this route, I would recommend using a JLabel and simply setting its ImageIcon rather than dragging JPanels.
I want to make a chess type board using a custom subclass of JButton. My problem is that my images of the chess pieces are a bit too small. Is there a way I can get the image to scale to exactly the size of each grid in my gridlayout? If I resize the Jframe, the grids will change size as well. Is there a way to get the image to resize dynamically upon resizing of the whole frame?
You have 3 option for this
1) Resize the images themselves using Gimp, Photoshop, etc.
2) Create an icon dynamically
Image i = icon.getImage();
if(i != null){
int width = (int)(size * fraction);
int height =(int)(size*icon.getIconHeight()/icon.getIconWidth()*fraction);
miniature = new ImageIcon(i.getScaledInstance(width, height, Image.SCALE_SMOOTH));
}
3) on the paint of your frame you can use scale
private void scaledDrawing(Graphics g, float scale){
Graphics2D g2 = (Graphics2D) g;
AffineTransform at = new AffineTransform();
AffineTransform save = g2.getTransform();
at.setToIdentity();
at.scale(goa.getScale().x, goa.getScale().y);
g2.transform(at);
image.paintIcon(c, g2);
g2.setTransform(save);
}
You could apply some transformation to the images but it might look a little ugly. If the images are small enough, maybe you can just force a minimum size of the button so that a scrollbar will appear if the frame is sized really small. Another option might be to have two or three different sets of the images at nicely scaled sizes, and swap them out for different board sizes.
Another alternative will be to override the paint function to fill all the available place:
#Override
public final void paint(final Graphics g) {
super.paint(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
Here is an example:
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
public final class Tileset extends Component {
private Image image;
public Tileset(final Image image) {
this.image = image;
}
#Override
public final void paint(final Graphics g) {
super.paint(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
public final Image getImage() {
return (image);
}
public final void setImage(final Image image) {
this.image = image;
}
}
With:
import javax.swing.JPanel;
import java.awt.GridLayout;
public final class Map extends JPanel {
public Map(final GridLayout layout) {
setLayout(layout);
}
public Map(final Integer width, final Integer height) {
this(new GridLayout(width, height));
}
}
And:
final Map map = new Map(13, 17);
final Image grass = new ImageIcon("src/main/res/tilesets/grass1.png").getImage();
final Image wood = new ImageIcon("src/main/res/tilesets/wood1.png").getImage();
final Image rock = new ImageIcon("src/main/res/tilesets/rock1.png").getImage();
for (int i = 0; i != 13; ++i) {
for (int j = 0; j != 17; ++j) {
if (i % 2 == 0) {
if (j % 2 == 0)
map.add(new Tileset(grass), i, j);
else
map.add(new Tileset(rock), i, j);
}
else
map.add(new Tileset(wood), i, j);
}
}
That will give you: