Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Creating an image

I'm currently working on a game in Java and am trying to create a background without using any image files. The image consists of a square split into 4 triangles, each of which is a different color.

If anyone could point me towards some was of using Graphics2D and then saving it to a BufferedImage, that would be great.

like image 368
Timr Avatar asked Apr 05 '13 02:04

Timr


People also ask

Can you do image processing with Java?

Java provides immediate access to the image pixels and color information and allows conversions and image processing.

What is an image in Java?

Image class is the superclass that represents graphical images as rectangular arrays of pixels. The java. awt. image. BufferedImage class, which extends the Image class to allow the application to operate directly with image data (for example, retrieving or setting up the pixel color).

How do I save a PNG file in Java?

The formatName parameter selects the image format in which to save the BufferedImage . try { // retrieve image BufferedImage bi = getMyImage(); File outputfile = new File("saved. png"); ImageIO. write(bi, "png", outputfile); } catch (IOException e) { ... }


1 Answers

I recommend:

  • First create a BufferedImage using the constructor that takes three ints: a width, height, and a BufferedImage type, BufferedImage.TYPE_INT_ARGB would probably work well, and the width and height will likely be constants in your program.
  • You would extract a Graphics2D object out of the BufferedImage by calling its createGraphics() method.
  • Then draw with the Graphics object using its drawXXX(...) methods of which you have many to select from.
  • To change color, simply call setColor(Color c) on your Graphics/Graphics2D object.
  • When done drawing, be sure to dispose of your Graphics object via its dispose() method.
  • Edit as per Adrian Blackburn, check out the BufferedImage Tutorial as part of the standard Oracle Java tutorials.
like image 184
Hovercraft Full Of Eels Avatar answered Sep 25 '22 16:09

Hovercraft Full Of Eels