Im coding a liitle game for java and want to make the Player look like a rocket, so i try to load the miage and then draw it on Java awt canvas.
Unfortunately i kepp gettin an IOException, but i dont get why... is the image some how wrong?
Thank you ver helpiNg me in advance and here`s the code:
(the image is in the same package as the Player class)
public class Player extends GameEntity {
private BufferedImage img;
public Player(int x, int y, ID id){
super(x, y , id);
}
BufferedImage loadImage(String fileName) {
BufferedImage bi = null;
//System.err.println("....setimg...." + fileName);
try {
bi = ImageIO.read(new File(fileName));
} catch (IOException e) {
e.printStackTrace();
System.out.println("Image could not be read");
System.exit(1);
}
return bi;
}
#Override
public void tick() {
x += velX;
y += velY;
}
#Override
public void render(Graphics graphics) {
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
BufferedImage rocketImage = loadImage("rocket.png");
Graphics2D g2d = (Graphics2D) graphics;
g2d.drawImage(rocketImage, at, null);
}
}
Related
I am currently having an issue with my code that it won't import an image from the file dialog. Basically it's meant to import the image when selected and place it on an Image Panel which is implemented.
Here is the code I have written for the File Import
FileDialog dialog = new FileDialog((Frame)null, "Select File to Open");
dialog.setMode(FileDialog.LOAD);
dialog.setVisible(true);
String file = dialog.getFile();
imageP.readImage(file);
imageP.repaint();
Here is the Image Panel Class
class ImagePanel extends JPanel
{
int numCols, numRows;
BufferedImage image = null;
private final int xOffset = 0;
private final int yOffset = 0;
public ImagePanel()
{
readImage("");
}
public void readImage(String filename)
{
try {
image = ImageIO.read(new File(filename));
numRows = image.getHeight();
numCols = image.getWidth();
}
catch( IOException e )
{
e.printStackTrace();
}
}
public void paintComponent( Graphics g )
{
Graphics2D g2 = (Graphics2D)g;
g2.clearRect(0, 0, this.getWidth(), this.getHeight());
if (image != null)
{
g2.drawImage( image, xOffset, yOffset, null );
}
}
}
I currently get an IIOException which says can't read file at the moment.
If anyone can help me with this issue that would be great.
I used some of the information around this site to find out to use URLs to get images into a jar file; which I want to be able to be used alone. But when I make the jar file with BlueJ, only some images show up.
Its a blackjack game, and only the table canvas shows up, while no cards ever do. Here's the code:
THIS WORKS (the table):
public class TableComponent extends JLabel{
BufferedImage table;
public TableComponent(){
URL finalTable = getClass().getResource("blackjackTableCanvas.jpg");
try {
table = ImageIO.read(finalTable);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
g2.drawImage(table, 0, 0, null);
}...}
but this does not (the cards):
public class CardRender2 extends JComponent{
BufferedImage image;
String val;
String suit;
String filename;
public CardRender2(Card card) {
this.val = card.value.face;
this.suit = card.suit.toString();
filename = this.fetchCardFileLabel();
URL cardview = getClass().getResource("\\card deck\\" + filename + ".png");
try {
image = ImageIO.read(cardview);
} catch (IOException e) {
e.printStackTrace();
}
}
public CardRender2(){
this.val = null;
this.suit = null;
filename = "DEALER_FIRST_CARD";
URL cardview = getClass().getResource("\\card deck\\DEALER_FIRST_CARD.png");
try {
image = ImageIO.read(cardview);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
g2.drawImage(image, 0, 0, null);
}...}
my cards are in a folder in the directory I try to import into BlueJ, whereas the table is in the directory root. There are 53 cards in there (incl dealer hidden card) and I'd rather not put all of then in the root. I tried to implement them similarly. How can I do this?
looks like changing from
URL cardview = getClass().getResource("\\card deck\\DEALER_FIRST_CARD.png");
to
URL cardview = getClass().getResource("card deck/DEALER_FIRST_CARD.png");
did the trick.
Hey,I'm trying to make a program which loads a colored image as grayscale on canvas and then returns the color to the pixels clicked.
I'm stuck here when the setrgb() method is not doing what its supposed to. I have copied the color from original image by getRGB() and am using setRGB() to assign it to a new image.
I have tried to output both the pixel color values but they are not same.
Please help me out with this.
Here's the code so far:
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.awt.*;
import java.applet.*;
#SuppressWarnings("serial")
public class BlackWHite extends Applet implements MouseListener
{
String str;
int x=0,y=0;
BufferedImage bimg = null;
BufferedImage nimg = null;
BufferedImage image=null;
double image_width =300;
double image_height=300;
private Image img;
public void init()
{
img = null;
str = JOptionPane.showInputDialog(null, "Enter file location : ",
"Choose Image", 1);
BufferedImage image=null;
try {
image = ImageIO.read(new File(str));
} catch (IOException e) {
e.printStackTrace();
}
//getting width and height of image
image_width = image.getWidth();
image_height = image.getHeight();
BufferedImage img = image;
//drawing a new image
bimg = new BufferedImage((int)image_width, (int)image_height,
BufferedImage.TYPE_BYTE_GRAY);
Graphics2D gg = bimg.createGraphics();
gg.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
nimg = new BufferedImage((int)image_width, (int)image_height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = nimg.createGraphics();
g.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
addMouseListener(this);
}
public void loadImage()
{
try {
img = getImage(getCodeBase(), "blackwhiteimage.jpg");
} catch(Exception e) {
}
}
public void paint(Graphics g)
{
try {
image = ImageIO.read(new File(str));
} catch (IOException e) {
e.printStackTrace();
}
convert(); //converting the image
if (img == null)
loadImage(); //draw
g.drawImage(img, 0, 0, this);
int c = image.getRGB(x,y);
int red = (c & 0x0000FFFF) >> 16;
int green = (c & 0x0000FFFF) >> 8;
int blue = c & 0x0000FFFF;
c=(red << 16) | (green << 8) | blue;
System.out.print("c="+c);
nimg=bimg;
nimg.setRGB(x,y,c);
try {
ImageIO.write(nimg, "jpg", new File("pixelcolor.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
g.drawImage(nimg, 0, 0, this);
int f = nimg.getRGB(x,y);
System.out.println("f="+f);
}
void convert() {
try {
//saving black and white image onto drive
ImageIO.write(bimg, "jpg", new File("blackwhiteimage.jpg"));
} catch (Exception e) {
System.out.println(e);
}
}
#Override
public void mouseClicked(MouseEvent me) {
x = me.getX();
y = me.getY();
repaint();
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent arg0) {
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
}
The fundamental problem is that you are trying to set the colour of the image in gray scale colour space. That is not the only bug in the applet, but you can start with it. Try using another way to convert the image to gray scale while keeping it in RGBA, such as those shown here: convert a RGB image to grayscale Image reducing the memory in java
How to crop images in Java? I currently have this class for image manipulation.
The main method with the run method:
public static void main(String[] args) {
GameProject gp = new GameProject();
gp.run();
}
public void run(){
s = new Screen();
try {
DisplayMode dm = s.findFirstCompatibleMode(modes);
s.setFullscreen(dm);
Fonts f = new Fonts(); //Checks if certain fonts exsist, if not install them.
Images i = new Images();
try {
i.draw("H:\\Dropbox\\Dropbox\\GameProject\\src\\Resources\\brock.png", 200, 200);
Thread.sleep(50000);
} catch (Exception e) {}
} finally {
s.restoreScreen();
}
}
Images class:
package Handlers;
import javax.swing.ImageIcon;
import java.awt.*;
/**
*
* #author Steven
*/
public class Images {
/**
* #param args the command line arguments
*/
private Screen s;
public void draw(String name, int x, int y) { //Draws the image
s = new Screen();
Graphics2D g = s.getGraphics();
draws(g, name, x, y, getWidth(name), getHeight(name));
}
public void drawA(String name, int x, int y){ //Draws the image, allows for a more advanced image manipulation
s = new Screen();
Graphics2D g = s.getGraphics();
draws(g, name, x, y, getWidth(name), getHeight(name));
}
public void draws(Graphics g, String name, int x, int y, int w, int h) { //Draws and updates the screen
s = new Screen();
g.drawImage(new ImageIcon(name).getImage(), x, y, w, h, null);
s.update();
}
public int getWidth(String name) { //Gets the image width
return new ImageIcon(name).getIconWidth();
}
public int getHeight(String name) { //Gets the images height
return new ImageIcon(name).getIconHeight();
}
}
Any help would be appreciated.
You can use CropImageFilter to crop images. Also, take a look at the java.awt.image package, it does have a lot of image manipulation routines.
I have used this in my own project :-
public boolean CropImage(int cropHeight,int cropWidth,int windowLeft,int windowTop,File srcFile,String destDirectory,String destFilename,int commonPadding,String fileFormat,HttpServletRequest request)throws IOException{
boolean isOkResolution=false;
try {
String dirPath=request.getRealPath("")+"/"+destDirectory;
File f=new File(dirPath);
if(!f.isDirectory()){
f.mkdir();
}
String destpath=dirPath+"/"+destFilename;
File outputFile=new File(destpath);
FileInputStream fis=new FileInputStream(srcFile);
BufferedImage bimage=ImageIO.read(fis);
System.out.println("Image Origilnal Height=="+bimage.getHeight());
BufferedImage oneimg=new BufferedImage(cropHeight,cropWidth,bimage.getType());
Graphics2D gr2d=oneimg.createGraphics();
isOkResolution=gr2d.drawImage(bimage,0,0,cropWidth,cropHeight,windowLeft-commonPadding,windowTop-commonPadding,(windowLeft+cropWidth)-commonPadding,(windowTop+cropHeight)-commonPadding,null);
gr2d.dispose();
ImageIO.write(oneimg,fileFormat,outputFile);
} catch (FileNotFoundException fe) {
System.out.println("No File Found =="+fe);
} catch(Exception ex){
System.out.println("Error in Croping File="+ex);
ex.printStackTrace();
}
return isOkResolution;
}
This method will help you to crop the image.Its working fine for my project.Hope it will help you out.
I'm trying to draw over an image (with the mouse) in a JPanel, this is working, but when I try to take an screenshot of the panel and generate an image of this, I only can see the image background without drawn with the mouse.
This is my code to generate the background Panel.java
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(this.createImage("/imagenes/cuerpoHumano.png").getImage(), 0, 0, null);
}
This is my code to draw as a pencil over the image: Panel.java
private void formMouseDragged(java.awt.event.MouseEvent evt) {
x = evt.getX();
y = evt.getY();
this.getGraphics().setColor(Color.RED);
this.getGraphics().fillOval(x, y, 4, 4);
}
This is the code to generate an screenshot
Dimension size = panel.getSize();
BufferedImage image = (BufferedImage) panel.createImage(size.width, size.height);
Graphics g = image.getGraphics();
panel.paint(g);
g.dispose();
try {
String fileName = UUID.randomUUID().toString().substring(0, 18);
ImageIO.write(image, "jpg", new File(path, fileName + ".jpg"));
} catch (IOException e) {
e.printStackTrace();
}
When you are taking the screenshot, the paintComponent() method is called. This means it will only paint you the image. You have to store the mouse move inside some model and paint the contents of the model in the paintComponent() method. This method is triggered by calling repaint() on the panel during the mouse move.
I think this is code that works .
public class PanelImagenCuerpoHumano extends JPanel {
private int x = -1;
private int y = -1;
private Image image = null;
private ArrayList<Point> puntos = new ArrayList<Point>();
public PanelImagenCuerpoHumano() {
image = new ImageIcon(getClass()
.getResource("/imagenes/cuerpoHumano.png")).getImage();
this.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
puntos.add(new Point(x, y));
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
}
});
}
#Override
protected void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
for (Point p : puntos) {
g.setColor(Color.red);
g.fillOval(p.x, p.y, 3, 3);
}
}
}