I'm looking for a good alternative to the javax.imageio package, that lets me do simple rotating, cutting and scaling operations on images. For example, I would like to do
int angle, height, width;
image.rotateRight(angle).scale(height, width);
in order to obtain an image that is rotated angle degrees to the right and scaled down to height x width pixels.
Using Graphics2D and BufferedImages, I will have to do this, which is neither readable, nor easy to write:
BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = result.createGraphics();
graphics.translate(height/2, width/2);
graphics.rotate(angle);
graphics.translate(-width/2, -height/2);
graphics.drawImage(image, 0, 0, width, height, null);
(Actually, that code doesn't even account for non-square images, which will require me to do even more magic with the translating).
There's the Java Advanced Imaging API which contains useful stuff like a RotatorDescriptor.
But I confess I find your above example pretty readable, so I'm not sure you'll get something more to your liking :-)
I agree with Brian: JAI is very good option for you. You may need to write some delegator object to get such readable code as you need and use it instead of JAI API.
Also you may use Processing (http://processing.org). It's API is simpler than JAI API. And as result of using Processing you'll get better quality for scaling and rotating operations by default.
Related
I'm making a small game in Java, and it uses a pixel-graphics style, with many sprites 16x16 or 32x32 pixels. However, when I rotate them, I do not want "jaggies" along the side, so I used the RenderingHint
RenderingHint.KEY_INTERPOLATION
RenderingHint.VALUE_INTERPOLATION_BILINEAR
Unfortunately, because many of the images used are very small (16x16, 32x32) the resulting image is completely unusable. Output:
http://imgur.com/a/roRh4
As you can see, the small graphics are blurred. This is the intended effect for large images, but for small images, it is very bad.
One solution is to increase the resolution of all my graphics, while keeping the "blocky" effect. That would be a pain, so is there another way to tweak the interpolation?
Thank you guys so much.
Upscale your tiny images and use that instead:
BufferedImage tiny = ImageIO.read(new File("..."));
BufferedImage bigger = new BufferedImage(tiny.getWidth()*10, tiny.getHeight()*10, tiny.getType());
Graphics2D g = bigger.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g.drawImage(tiny, 0, 0, bigger.getWidth(), bigger.getHeight(), 0, 0, tiny.getWidth(), tiny.getHeight(), null);
Replace the 10 scaling factor by the smallest value that gives acceptable results.
Do the rest of your rendering with high quality interpolation.
I do not know java (usually write in c)
How can I do efficiently some way of blitting
pixel array content onto a window in java?
I need (in loop) blit pixels[][] onto a window
I could use something like
pixels[][] -> MemoryImageSource -> Image -> drawImage
but creating and deleting MemoryImageSource and Image
in every frame seems strange to me - how it can be
done simply and reasonably efficiently? Could someone
give a code example, tnx
Normally in Java it's easier to work with the native Image types and use their derived graphics. Behind the scenes Java uses blits as well, so the higher level abstractions is made to easen the workload.
But if there's no way to abstract on the pixel data you can use Raster and WritableRaster (where you can replace portions of the array) as an alternative to your solution. These rasters can be used with a BufferedImage which then can be drawn using the drawImage method you mentioned. I found one way of doing it here which basically creates the Image and then retrieves the raster for future manipulation.
int x, y = 100;
BufferedImage image = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
WritableRaster raster = image.getRaster();
That raster (or just small areas of it) can then be manipulated and repainted.
This might improve performance slightly since the distance from you pixel-array to the screen is shorter. But I think very few people fully understands the entire depths of the AWT api - and it all depends on the native implementations of course - so my idea contains a healthy part of speculation ;-)
But I hope it helped..
For speed, you can pre-compute variations of the ColorModel, as shown in this example.
One attempted approach was to use TexturePaint and g.fillRect() to paint the image. This however requires you to create a new TexturePaint and Rectangle2D object each time you paint an image, which isn't ideal - and doesn't help anyway.
When I use g.drawImage(BufferedImage,...), the rotated images appear to be blurred/soft.
I'm familiar with RenderingHints and double-buffering (which is what I'm doing, I think), I just find it difficult to believe that you can't easily and efficiently rotate an image in Java that produces sharp results.
Code for using TexturePaint looks something like this.
Grahics2D g2d = (Graphics2D)g;
g2d.setPaint(new TexturePaint(bufferedImage, new Rectangle2D.Float(0,0,50,50)));
g2d.fillRect(0,0,50,50);
I'm using AffineTransform to rotate a hand of cards into a fan.
What would be the best approach to paint good-looking images quickly?
Here is a screenshot:
The 9 is crisp but the rest of the cards are definitely not as sharp.
It could be possible that the problem lies in when I create each card image and store it in an array.
Here's how I'm doing it at the moment:
// i from 0 to 52, card codes.
...
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
BufferedImage img = gc.createCompatibleImage(86, 126, Transparency.TRANSLUCENT);
Graphics2D g = img.createGraphics();
setRenderingHints(g);
g.drawImage(shadow, 0, 0, 86, 126, null);
g.drawImage(white, 3, 3, 80, 120, null);
g.drawImage(suit, 3, 3, 80, 120, null);
g.drawImage(value, 3, 3, 80, 120, null);
g.dispose();
cardImages[i] = img;
}
private void setRenderingHints(Graphics2D g){
g.setRenderingHint(KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON);
}
How should I approach this differently?
Thanks.
Edit:
Without RenderingHints
Setting AA hints made no difference. Also, setting RenderingHints when creating the images makes no difference either. It's only when they are being rotated with AffineTransform and painted using g.drawImage(...) that they seem to blur. The image above shows the difference between default (nearest neighbor) and bilinear interpolation.
Here is how I'm currently painting them (much faster than TexturePaint):
// GamePanel.java
private void paintCard(Graphics2D g, int code, int x, int y){
g.drawImage(imageLoader.getCard(code), x, y, 86, 126, null);
}
// ImageLoader.java
public BufferedImage getCard(int code){
return cardImages[code];
}
All my cards are 80x120 and the shadow .png is 86x126, so as to leave 3px semi-transparent shadow around the card. It's not a realistic shadow I know, but it looks okay.
And so the question becomes... How can you produce sharp paint results when rotating a BufferedImage?
Reference to a previous question also regarding a fanned card hand:
How can you detect a mouse-click event on an Image object in Java?
Bounty-Edit:
Okay so after much discussion I made a few test .svg cards to see how SVG Salamander would go about rendering them. Unfortunately, the performance is terrible. My implementation is clean enough, seeing as with double-buffered BufferedImage's the painting was incredibly fast. Which means I have come full circle and I'm back to my original problem.
I'll give the 50 bounty to whoever can give me a solution to get sharp BufferedImage rotations. Suggestions have been to make the images bigger than they need to be and downscale before painting, and to use bicubic interpolation. If these are the only possible solutions, then I really don't know where to go from here and I may just have to deal with the blurred rotations - because both of those impose performance setbacks.
I can finish my game if I can find a way to do this well.
Thanks to everyone. :)
When you rotate a rasterized image (such as a BufferedImage), you lose data. The best solution is to save your images larger than you'll need them, and downscale on the fly when you paint them. I've found that 1.5x the size you need is a good starting point.
Then, when you're painting the image, resize on the fly:
g.drawImage(bufferedImage, x, y, desiredWidth, desiredHeight, observer);
Rotations using bilinear interpolation is recommended.
Credit for suggestion goes to guido.
This advice is probably a little late in your design, but may be worth mentioning.
Rasterized images is probably the wrong technology to use if a lot of rotations and animations are a part of your UI; especially with complicated images with lots of curves. Just wait until you try and scale your canvass. I might suggest looking at a vector based graphical library. They will render the sorts of effects you want with less potential for artifacts.
http://xmlgraphics.apache.org/batik/using/swing.htm
Setting the interpolation type, as well as anti-aliasing value, in an AffineTransformOp may offer some improvement. Type TYPE_BICUBIC, while slower, is typically the best quality; an example is outlined here. Note that you can supply multiple RenderingHints. Another pitfall arises from failing to apply the hints each time the image is rendered. You may also need to adjust the transparency of the background, as suggested here. Finally, consider creating an sscce that includes one of your actual images.
I have a BufferedImage with an IndexColorModel. I need to paint that image onto the screen, but I've noticed that this is slow when using an IndexColorModel. However, if I run the BufferedImage through an identity affine transform it creates an image with a DirectColorModel and the painting is significantly faster. Here's the code I'm using
AffineTransformOp identityOp = new AffineTransformOp(new AffineTransform(), AffineTransformOp.TYPE_BILINEAR);
displayImage = identityOp.filter(displayImage, null);
I have three questions
1. Why is painting the slower on an IndexColorModel?
2. Is there any way to speed up the painting of an IndexColorModel?
3. If the answer to 2. is no, is this the most efficient way to convert from an IndexColorModel to a DirectColorModel? I've noticed that this conversion is dependent on the size of the image, and I'd like to remove that dependency.
Thanks for the help
This is too long for a comment...
Are you sure that the BufferedImage you're creating are the best depending on the OS you're on? You should always create a "compatible" BufferedImage. The fastest on, say, Windows, may be TYPE_INT_ARGB but this is not true on OS X and vice-versa.
Something like this (ouch, the Law of Demeter hurts ;) :
GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration()
.createCompatibleImage(width, height,Transparency.TRANSLUCENT)
I resized an image using Java2D Graphics class. But it doesn't look right.
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
Is it possible to scale an image without introducing artifacts?
Bitmap graphics do not scale well, generally speaking. Degradation is particularly notable when you increase the size of the image, but even scaling down can introduce undesirable artifacts especially if not scaling by integral factors.
The best solution, if you need multiple sizes of a single image for display, is to either use vector* graphics or take the highest fidelity bitmap you have and scale down, and by integral factors.
*Note that vector graphics aren't an option for photographs and the like.
This article by Chris Campbell has lots of detailed information on scaling images with Java2D.
There are a number of options you can use regarding the quality of the scaling, where generally the better the quality the longer the scaling will take (performance versus quality tradeoff).
The information in the article will probably help your scaling look better, but as #Kevin says in his answer, at the end of the day no scaling is going to be absolutely perfect.
You could look into java-image-scaling library. With a quick test it created a better quality down scaled image than using standard Java2D/AWT tools.