13

I have been searching google for stuff like "Java Bitmap", "Create Java Bitmap", etc and cannot seem to find much information. From all of the code examples it looks like all of the bitmap libraries are third party or for android.

What I want to do is very simple. I want to create a small bitmap maybe 10x80, and be able to color each pixel at (x,y). I want to make a small I guess color bar that will show that position of items in a queue by color.

Are there any build in libraries to do this?

KDecker
  • 6,928
  • 8
  • 40
  • 81

2 Answers2

13

There's the java.awt.image.BufferedImage class. This has pixel-specific get/set methods. http://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImage.html

ceztko
  • 14,736
  • 5
  • 58
  • 73
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Note that if you plan on modifying the pixels of the image, then it is better to use a [VolatileImage](http://docs.oracle.com/javase/7/docs/api/java/awt/image/VolatileImage.html). This is because `VolatileImage`s are hardware accelerated even when their pixels are being modified. – BitNinja Sep 07 '14 at 20:01
  • @ceztko Thanks for the fix – khelwood Dec 05 '18 at 12:59
8

Here is an example of creating and writing to pixels with BufferedImage:

BufferedImage image = new BufferedImage(10, 80, BufferedImage.TYPE_4BYTE_ABGR);
image.setRGB(5, 20, Color.BLUE.getRGB());

The third parameter on the image is the type, which may vary based on your use, but for basic solid colors the one shown is good. The setRGB uses an int representation of the color so you can't just use a Color constant directly.

You probably don't want to use VolatileImage because the benefits are dubious in current Java implementations. See this stackoverflow question for why it may not help.

Look at the Oracle image turorial for help with this. It explains both your options and how to interact with them.

Community
  • 1
  • 1
Eben
  • 422
  • 2
  • 11
  • why the downvote for providing the official tutorial for this question? – Eben Sep 07 '14 at 20:08
  • 1
    I didn't downvote, but this answer is essentially link-only, which is frowned upon here. I know that sometimes it seems perfectly valid, but the fact is that this link might someday become obsolete. The way to fix this would be to summarize that tutorial in your answer. – BitNinja Sep 07 '14 at 20:19
  • Thanks for the explanation, I'll add an appropriate summary. – Eben Sep 07 '14 at 20:49