On the first time through, I insert BufferedImages from a list onto my JPanel from my extended class:
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
if (controlWhichImage == 1){
for (BufferedImage eachImage : docList){
g.drawImage(eachImage, 0,inty,imageWidth,imageHeight,null);
intx += eachImage.getWidth();
inty += eachImage.getHeight() * zoomAdd;
}
if (intx >= this.getWidth() || inty >= this.getHeight()){
inty = 0;
}
The next time I want to copy the contents of the JPanel to a BufferedImage:
public void recordImage(){
controlWhichImage = 2;
this.createdImage = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
Image halfWay = this.createImage(this.getWidth(), this.getHeight());
//now cast it from Image to bufferedImage
this.createdImage = (BufferedImage) halfWay;
}
And then, take the modified BufferedImage and draw it back onto the JPanel:
if (controlWhichImage == 2){
g.drawImage(this.createdImage,0,inty,this.getWidth(),this.getHeight(),null);
}
This second time I get a blank panel.
I hope this is clear, any help gratefully received.
Sorry for my poor explanation. I will try to make myself clearer.
On each iteration the user is able to draw on the image in the Jpanel.
What I want to do is copy the user altered jpanel into a buffered image which will then be in the Jpanel to be edited again by the user.
This continues until the user selects print.
So apart from the code that I have put here are the controls for drawing by the user, at the moment I am struggling with putting the initial updated image from the original Jpanel into a bufferedImage and then back to the JPanel.
Hope this makes it somewhat clearer
To draw to a BufferedImage, you would do something similar to what you already do in your paintComponent method, but with your BufferedImage. Perhaps a method like:
// imgW and imgH are the width and height of the desired ultimate image
public BufferedImage combineImages(List<BufferedImage> docList, int imgW, int imgH) {
// first create the main image that you want to draw to
BufferedImage mainImg = new BufferedImage(imgW, imgH, BufferedImage.TYPE_INT_ARGB);
// get its Graphics context
Graphics g = mainImage.getGraphics();
int intx = 0;
int inty = 0;
// draw your List of images onto this main image however you want to do this
for (BufferedImage eachImage : docList){
g.drawImage(eachImage, 0,inty,imageWidth,imageHeight,null);
intx += eachImage.getWidth();
inty += eachImage.getHeight() * zoomAdd;
}
}
// anything else that you need to do
g.dispose(); // dispose of this graphics context to save resources
return mainImg;
}
You could then store the image returned into a varaible and then draw it in your JPanel if desired, or write it to disk.
If this doesn't answer your question, then again you'll want to tell more and show us your MCVE.
Related
Currently I am saving a jtable as jpeg using the below method, when the dimension of the jtable became 2590, 126181, java.lang.OutOfMemoryError: Java heap space exception occurs at "BufferedImage constructor", when the size of the table is small the image gets saved successfully.
public BufferedImage saveComponentAsJPEG(JTable table, String filename) {
Dimension size = table.getSize();
BufferedImage myImage =
new BufferedImage(size.width, size.height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = myImage.createGraphics();
table.paint(g2);
return myImage;
}
How to save a jtable with bigger size in pdf or jpeg image?
Updated Info:
You asked how to "split the JTable into different small images":
As you go through my code below please read my comments, they help explain what is happening and will help you grasp a better understanding of how a JTable/JComponent can be painted to lots of small images. At the heart my code is similar to yours, but there are two key points:
1) Rather than create a single large BufferedImage, I create a single small image that is then used multiple times, therefore leaving a very small memory footprint.
2) With the single image, I use Graphics.translate() to paint a small part of the JTable each time.
The following code was tested with a large JComponents (2590 x 126181) and a tile size of 200x200, and the whole process did not exceed 60mb of memory:
//width = width of tile in pixels, for minimal memory usage try 200
//height = height of tile in pixels, for minimal memory usage try 200
//saveFileLocation = folder to save image tiles
//component = The JComponent to save as tiles
public static boolean saveComponentTiles(int width, int height, String saveFileLocation, JComponent component)
{
try
{
//Calculate tile sizes
int componentWidth = component.getWidth();
int componentHeight = component.getHeight();
int horizontalTiles = (int) Math.ceil((double)componentWidth / width); //use (double) so Math.ceil works correctly.
int verticalTiles = (int) Math.ceil((double)componentHeight / height); //use (double) so Math.ceil works correctly.
System.out.println("Tiles Required (H, W): "+horizontalTiles+", verticalTiles: "+verticalTiles);
//preset arguments
BufferedImage image;
//Loop through vertical and horizontal tiles
//Draw part of the component to the image
//Save image to file
for (int h = 0; h < verticalTiles; h++)
{
for (int w = 0; w < horizontalTiles; w++)
{
//check tile size, if area to paint is smaller than image then shrink image
int imageHeight = height;
int imageWidth = width;
if (h + 1 == verticalTiles)
{
imageHeight = componentHeight - (h * height);
}
if (w + 1 == horizontalTiles)
{
imageWidth = componentWidth - (w * width);
}
image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
//translate image graphics so that only the correct part of the component is panted to the image
g.translate(-(w * width), -(h * height));
component.paint(g);
//In my example I am saving the image to file, however you could throw your PDF processing code here
//Files are named as "Image.[h].[w]"
//Example: Image 8 down and 2 accross would save as "Image.8.2.png"
ImageIO.write(image, "png", new File(saveFileLocation + "Image." + h +"."+ w + ".png"));
//tidy up
g.dispose();
}
}
return true;
}
catch (IOException ex)
{
return false;
}
}
Just call it like so:
boolean result = saveComponentTiles(200, 200, saveFileLocation, jTable1);
Also if you haven't done it already, you should only call the method from a different thread because it will hang your application when dealing with large components.
If you have not picked a PDF library yet, then I highly recommend looking at iText.
Original Post:
The process you are looking for is quite simple, however it may take some work.
You were on the right track thinking about parts, but as David
mentioned you shouldn't mess with the jTable, instead you will need a
to make use of the TiledImage class, or do something yourself with
RenderedImage and Rasters.
This sort of method basically uses HDD space instead of memory and
lets you create a large image in lots of smaller parts/tiles, then
when its done you can save it all to a single image file.
This answer may also help: https://stackoverflow.com/a/14069551/1270000
I'm having performance oddities with Java2D. I know of the sun.java2d.opengl VM parameter to enable 3D acceleration for 2D, but even using that has some weird issues.
Here are results of tests I ran:
Drawing a 25x18 map with 32x32 pixel tiles on a JComponent
Image 1 = .bmp format, Image 2 = A .png format
Without -Dsun.java2d.opengl=true
120 FPS using .BMP image 1
13 FPS using .PNG image 2
With -Dsun.java2d.opengl=true
12 FPS using .BMP image 1
700 FPS using .PNG image 2
Without acceleration, I'm assuming some kind of transformation is taking place with every drawImage() I do in software, and is pulling down the FPS considerably in the case of .PNG. Why though, with acceleration, would the results switch (and PNG actually performs incredibly faster)?! Craziness!
.BMP Image 1 is translated to an image type of TYPE_INT_RGB. .PNG Image 2 is translated to an image type of TYPE_CUSTOM. In order to get consistent speed with and without opengl acceleration, I have to create a new BufferedImage with an image type of TYPE_INT_ARGB, and draw Image 1 or Image 2 to this new image.
Here are the results running with that:
Without -Dsun.java2d.opengl=true
120 FPS using .BMP image 1
120 FPS using .PNG image 2
With -Dsun.java2d.opengl=true
700 FPS using .BMP image 1
700 FPS using .PNG image 2
My real question is, can I assume that TYPE_INT_ARGB will be the native image type for all systems and platforms? I'm assuming this value could be different. Is there some way for me to get the native value so that I can always create new BufferedImages for maximum performance?
Thanks in advance...
I think I found a solution by researching and putting bits and pieces together from too many Google searches.
Here it is, comments and all:
private BufferedImage toCompatibleImage(BufferedImage image)
{
// obtain the current system graphical settings
GraphicsConfiguration gfxConfig = GraphicsEnvironment.
getLocalGraphicsEnvironment().getDefaultScreenDevice().
getDefaultConfiguration();
/*
* if image is already compatible and optimized for current system
* settings, simply return it
*/
if (image.getColorModel().equals(gfxConfig.getColorModel()))
return image;
// image is not optimized, so create a new image that is
BufferedImage newImage = gfxConfig.createCompatibleImage(
image.getWidth(), image.getHeight(), image.getTransparency());
// get the graphics context of the new image to draw the old image on
Graphics2D g2d = newImage.createGraphics();
// actually draw the image and dispose of context no longer needed
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
// return the new optimized image
return newImage;
}
In my previous post, GraphicsConfiguration was what held the information needed to create optimized images on a system. It seems to work pretty well, but I would have thought Java would automatically do this for you. Obviously you can't get too comfortable with Java. :) I guess I ended up answering my own question. Oh well, hopefully it'll help some of you I've seen trying to make use of Java for 2D games.
Well, this is old post but I'd like to share my findings about direct drawing with Swing/AWT, without BufferedImage.
Some kind of drawing, as 3D, are better done when painting directly to a int[] buffer. Once done the images, you can use an ImageProducer instance, like MemoryImageSource, to produce images. I'm assuming you know how to perform your drawings directly, without help of Graphics/Graphics2.
/**
* How to use MemoryImageSource to render images on JPanel
* Example by A.Borges (2015)
*/
public class MyCanvas extends JPanel implements Runnable {
public int pixel[];
public int width;
public int height;
private Image imageBuffer;
private MemoryImageSource mImageProducer;
private ColorModel cm;
private Thread thread;
public MyCanvas() {
super(true);
thread = new Thread(this, "MyCanvas Thread");
}
/**
* Call it after been visible and after resizes.
*/
public void init(){
cm = getCompatibleColorModel();
width = getWidth();
height = getHeight();
int screenSize = width * height;
if(pixel == null || pixel.length < screenSize){
pixel = new int[screenSize];
}
mImageProducer = new MemoryImageSource(width, height, cm, pixel,0, width);
mImageProducer.setAnimated(true);
mImageProducer.setFullBufferUpdates(true);
imageBuffer = Toolkit.getDefaultToolkit().createImage(mImageProducer);
if(thread.isInterrupted() || !thread.isAlive()){
thread.start();
}
}
/**
* Do your draws in here !!
* pixel is your canvas!
*/
public /* abstract */ void render(){
// rubisch draw
int[] p = pixel; // this avoid crash when resizing
if(p.length != width * height) return;
for(int x=0; x < width; x++){
for(int y=0; y<height; y++){
int color = (((x + i) % 255) & 0xFF) << 16; //red
color |= (((y + j) % 255) & 0xFF) << 8; //green
color |= (((y/2 + x/2 - j) % 255) & 0xFF) ; //blue
p[ x + y * width] = color;
}
}
i += 1;
j += 1;
}
private int i=1,j=256;
#Override
public void run() {
while (true) {
// request a JPanel re-drawing
repaint();
try {Thread.sleep(5);} catch (InterruptedException e) {}
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// perform draws on pixels
render();
// ask ImageProducer to update image
mImageProducer.newPixels();
// draw it on panel
g.drawImage(this.imageBuffer, 0, 0, this);
}
/**
* Overrides ImageObserver.imageUpdate.
* Always return true, assuming that imageBuffer is ready to go when called
*/
#Override
public boolean imageUpdate(Image image, int a, int b, int c, int d, int e) {
return true;
}
}// end class
Note we need unique instance of MemoryImageSource and Image. Do not create new Image or new ImageProducer for each frames, unless you have resized your JPanel. See init() method above.
In a rendering thread, ask a repaint(). On Swing, repaint() will call the overridden paintComponent(), where it call your render() method and then ask your imageProducer to update image.
With Image done, draw it with Graphics.drawImage().
To have a compatible Image, use proper ColorModel when you create your Image. I use GraphicsConfiguration.getColorModel():
/**
* Get Best Color model available for current screen.
* #return color model
*/
protected static ColorModel getCompatibleColorModel(){
GraphicsConfiguration gfx_config = GraphicsEnvironment.
getLocalGraphicsEnvironment().getDefaultScreenDevice().
getDefaultConfiguration();
return gfx_config.getColorModel();
}
From what I remember when I was thinking about doing graphics programming in Java, the built in libraries are slow. I was advised on GameDev.Net that anyone doing anything serious would have to use something like jogl
Long story short I am drawing the Mandelbrot using a BufferedImage that I put in a custom JPanel. I have already done the zooming in the set but have problems with repainting when unzooming. When unzooming I change the value of the image to that of the previous state of the image(I keep every state in a Stack) and repaint the panel. Problem is that the last image in the stack gets popped off but it is not drawn.
These are my instance variables
private BufferedImage image = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
private Stack<BufferedImage> zooms = new Stack<BufferedImage>();
private boolean unzoom = false;
This is how I zoom and push the image that I want to save on a stack
public void mouseReleased(MouseEvent e)
{
zooms.push(image);
<some code for zooming that works>
repaint();
}
Now I want to unzoom by scrolling
class WheelZoomListener implements MouseWheelListener
{
public void mouseWheelMoved(MouseWheelEvent e)
{
unzoom = true;
//this is how I assign the current image to be the one before the last zoom
image = zooms.pop();
repaint();
}
}
Finally this is my paint method
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d= (Graphics2D) g;
//if it is not unzooming draw the mandelbrot set normally by
//dealing with every pixel of the Buffered Image separately
if (!unzoom)
{
for(int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
int iterations = getIterations(cnSet[i][j]);
if (iterations == noIterations)
{
color = Color.BLACK;
}
else
{
color = cols[iterations%noIterations];
}
image.setRGB(i, j, color.getRGB());
}
}
}
//zooming or unzooming always draw the image in its current state
g2d.drawImage(image, 0, 0, this);
unzoom = false;
}
FIX: It turned out that I don't need to keep the last image and create temporary images every time. Instead now I only keep the coordinates of the complex plane in a stack. That is all I need to repaint the old image again.
This:
private BufferedImage image = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
Instantiates a new BufferedImage and stores a reference to that object in image.
This:
zooms.push(image);
Pushes the reference to that single BufferedImage you created onto the stack.
As long as you keep using the same BufferedImage, all you are doing is pushing multiple references to the same object onto the stack; so changes to the object's data are reflected in every reference you've placed on the stack, because every item in the stack points to the same object.
The high-level effect is you are changing every previous state to the current one every time you render.
You'll want to create a whole new BufferedImage for each state; so that each reference you stick on the stack points to a unique object.
Take a look at this nice little article about how references work in Java.
I have a JPanel that has some JLabels on it. They've been set to specific sizes based on the size of the JPanel. However, when I resize the JPanel, they don't get resized. What I would like to do is force them to get resized. Here was my attempt:
public void componentResized(ComponentEvent e) {
//just test values
int height = 10;
int width = 10;
Dimension d = new Dimension(width, height);
//whenever we detect this event, we'll resize the draft components
for(int i = 0; i < jpPack.getComponentCount(); i++){
jpPack.getComponent(i).setPreferredSize(d);
}
jpPack.revalidate();
jpPack.repaint();
}
However, this didn't work, I didn't get any results. I also tried with setSize(d) but nothing either. The way I've created it right now, the size of the JLabel is set at creation based on the size of the JPanel.
Essentially, all I want to do is tell the JLabel "the GUI has resized, here is your new size, now repaint yourself to be this size". Would I perhaps have to change my JLabel's paint method to handle this? If so, how would I go about that?
Thanks.
EDIT: Here is some additional information to try to help. I'm sorry I can't provide a working example, but there's just so much code involved in making this work and it isn't feasible (it's not a small project, it's a minor bug in a large project).
ImageLabels are my custom JLabel to use for my cards. There isn't a lot in there besides some stored data and compare methods. The paintComponent method when drawing the cards in the images below should just be calling the super method.
My JPanel containing the labels is defined as follows:
jpCards = new JPanel(new MigLayout("insets 0, gapx 0, gapy 0, rtl", "grow"));
When I add images, they are added as follows:
for(int i = 0; i < imgJLabels.length; i++){
BufferedImage img;
try{
img = ImageIO.read(new URL(XML.getXML().getCardURLByName(pack[i], set)));
}
catch (java.net.MalformedURLException e){
}
int height = (jpPack.getHeight() / 2);
if(height > 310) height = 310;
float temp = (float)img.getWidth() / img.getHeight();
int width = Math.round(height * temp);
if(width > 223) width = 223;
ImageIcon imgIcon = getScaledImage(img, height, width);
imgJLabels[i] = new ImageLabel(img, imgIcon, pack[i]);
jpPack.add(imgJLabels[i]);
imgJLabels[i].addMouseListener(this);
}
And my scaling method is as follows:
private ImageIcon getScaledImage(Image srcImg, int height, int width){
BufferedImage resizedImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, width, height, null);
g2.dispose();
return new ImageIcon(resizedImg);
}
Here you can see the results. As I resize the GUI to be bigger, the ImageLabels don't increase in size. The same applies when I make the GUI smaller, the cards don't become smaller.
I do have a maximum size for the cards set, as you can see. However, the large card image on the right is set to the same maximum, so my cards are definitely not hitting the maximum. The GUI is just not resizing the elements.
This issue has been driving me nuts for a long time and I have no idea what to do. Thanks again.
I'm having performance oddities with Java2D. I know of the sun.java2d.opengl VM parameter to enable 3D acceleration for 2D, but even using that has some weird issues.
Here are results of tests I ran:
Drawing a 25x18 map with 32x32 pixel tiles on a JComponent
Image 1 = .bmp format, Image 2 = A .png format
Without -Dsun.java2d.opengl=true
120 FPS using .BMP image 1
13 FPS using .PNG image 2
With -Dsun.java2d.opengl=true
12 FPS using .BMP image 1
700 FPS using .PNG image 2
Without acceleration, I'm assuming some kind of transformation is taking place with every drawImage() I do in software, and is pulling down the FPS considerably in the case of .PNG. Why though, with acceleration, would the results switch (and PNG actually performs incredibly faster)?! Craziness!
.BMP Image 1 is translated to an image type of TYPE_INT_RGB. .PNG Image 2 is translated to an image type of TYPE_CUSTOM. In order to get consistent speed with and without opengl acceleration, I have to create a new BufferedImage with an image type of TYPE_INT_ARGB, and draw Image 1 or Image 2 to this new image.
Here are the results running with that:
Without -Dsun.java2d.opengl=true
120 FPS using .BMP image 1
120 FPS using .PNG image 2
With -Dsun.java2d.opengl=true
700 FPS using .BMP image 1
700 FPS using .PNG image 2
My real question is, can I assume that TYPE_INT_ARGB will be the native image type for all systems and platforms? I'm assuming this value could be different. Is there some way for me to get the native value so that I can always create new BufferedImages for maximum performance?
Thanks in advance...
I think I found a solution by researching and putting bits and pieces together from too many Google searches.
Here it is, comments and all:
private BufferedImage toCompatibleImage(BufferedImage image)
{
// obtain the current system graphical settings
GraphicsConfiguration gfxConfig = GraphicsEnvironment.
getLocalGraphicsEnvironment().getDefaultScreenDevice().
getDefaultConfiguration();
/*
* if image is already compatible and optimized for current system
* settings, simply return it
*/
if (image.getColorModel().equals(gfxConfig.getColorModel()))
return image;
// image is not optimized, so create a new image that is
BufferedImage newImage = gfxConfig.createCompatibleImage(
image.getWidth(), image.getHeight(), image.getTransparency());
// get the graphics context of the new image to draw the old image on
Graphics2D g2d = newImage.createGraphics();
// actually draw the image and dispose of context no longer needed
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
// return the new optimized image
return newImage;
}
In my previous post, GraphicsConfiguration was what held the information needed to create optimized images on a system. It seems to work pretty well, but I would have thought Java would automatically do this for you. Obviously you can't get too comfortable with Java. :) I guess I ended up answering my own question. Oh well, hopefully it'll help some of you I've seen trying to make use of Java for 2D games.
Well, this is old post but I'd like to share my findings about direct drawing with Swing/AWT, without BufferedImage.
Some kind of drawing, as 3D, are better done when painting directly to a int[] buffer. Once done the images, you can use an ImageProducer instance, like MemoryImageSource, to produce images. I'm assuming you know how to perform your drawings directly, without help of Graphics/Graphics2.
/**
* How to use MemoryImageSource to render images on JPanel
* Example by A.Borges (2015)
*/
public class MyCanvas extends JPanel implements Runnable {
public int pixel[];
public int width;
public int height;
private Image imageBuffer;
private MemoryImageSource mImageProducer;
private ColorModel cm;
private Thread thread;
public MyCanvas() {
super(true);
thread = new Thread(this, "MyCanvas Thread");
}
/**
* Call it after been visible and after resizes.
*/
public void init(){
cm = getCompatibleColorModel();
width = getWidth();
height = getHeight();
int screenSize = width * height;
if(pixel == null || pixel.length < screenSize){
pixel = new int[screenSize];
}
mImageProducer = new MemoryImageSource(width, height, cm, pixel,0, width);
mImageProducer.setAnimated(true);
mImageProducer.setFullBufferUpdates(true);
imageBuffer = Toolkit.getDefaultToolkit().createImage(mImageProducer);
if(thread.isInterrupted() || !thread.isAlive()){
thread.start();
}
}
/**
* Do your draws in here !!
* pixel is your canvas!
*/
public /* abstract */ void render(){
// rubisch draw
int[] p = pixel; // this avoid crash when resizing
if(p.length != width * height) return;
for(int x=0; x < width; x++){
for(int y=0; y<height; y++){
int color = (((x + i) % 255) & 0xFF) << 16; //red
color |= (((y + j) % 255) & 0xFF) << 8; //green
color |= (((y/2 + x/2 - j) % 255) & 0xFF) ; //blue
p[ x + y * width] = color;
}
}
i += 1;
j += 1;
}
private int i=1,j=256;
#Override
public void run() {
while (true) {
// request a JPanel re-drawing
repaint();
try {Thread.sleep(5);} catch (InterruptedException e) {}
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// perform draws on pixels
render();
// ask ImageProducer to update image
mImageProducer.newPixels();
// draw it on panel
g.drawImage(this.imageBuffer, 0, 0, this);
}
/**
* Overrides ImageObserver.imageUpdate.
* Always return true, assuming that imageBuffer is ready to go when called
*/
#Override
public boolean imageUpdate(Image image, int a, int b, int c, int d, int e) {
return true;
}
}// end class
Note we need unique instance of MemoryImageSource and Image. Do not create new Image or new ImageProducer for each frames, unless you have resized your JPanel. See init() method above.
In a rendering thread, ask a repaint(). On Swing, repaint() will call the overridden paintComponent(), where it call your render() method and then ask your imageProducer to update image.
With Image done, draw it with Graphics.drawImage().
To have a compatible Image, use proper ColorModel when you create your Image. I use GraphicsConfiguration.getColorModel():
/**
* Get Best Color model available for current screen.
* #return color model
*/
protected static ColorModel getCompatibleColorModel(){
GraphicsConfiguration gfx_config = GraphicsEnvironment.
getLocalGraphicsEnvironment().getDefaultScreenDevice().
getDefaultConfiguration();
return gfx_config.getColorModel();
}
From what I remember when I was thinking about doing graphics programming in Java, the built in libraries are slow. I was advised on GameDev.Net that anyone doing anything serious would have to use something like jogl