I'm kinda doing a GUI where when you press the "NEXT" button, it shows one by one the images at some directory.
My question is: How can I fit the size of the IMGs with the JPanles dimensions, I'm working with 6 or more MP images and I need to see the entire image.
Here is the code that gives me the imageIcon and where I add it to the JPanel.
JButton btnNextImg = new JButton("Next IMG");
btnNextImg.setBounds(96, 179, 110, 23);
btnNextImg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (i == nImg)
i = 0;
try {
selectedImage = ImageIO.read(new File("C:\\IMAGES\\"+ String.valueOf(i+1) + ".jpg"));
iSelect = new ImageIcon(selectedImage);
originalImage.setIcon(iSelect);
} catch (IOException e1) {
e1.printStackTrace();
}
i++;
}
});
contentPane.add(btnNextImg);
And where I add it.
JPanel panel = new JPanel();
originalImage = new JLabel();
panel.add(originalImage);
panel.setBounds(5, 226, 309, 280);
contentPane.add(panel);
Thank you so much.
here's an image panel i found somewhere on the internet when i had the same problem:
public class ImagePanel extends JPanel {
private java.awt.Image image;
private boolean stretched = true;
private int xCoordinate;
private int yCoordinate;
public ImagePanel() {
}
public ImagePanel(Image image) {
this.image = image;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
if (isStretched()) {
g.drawImage(image, xCoordinate, yCoordinate, getWidth(), getHeight(), this);
} else {
g.drawImage(image, xCoordinate, yCoordinate, this);
}
}
}
public java.awt.Image getImage() {
return image;
}
public void setImage(java.awt.Image image) {
this.image = image;
repaint();
}
public boolean isStretched() {
return stretched;
}
public void setStretched(boolean stretched) {
this.stretched = stretched;
repaint();
}
public int getXCoordinate() {
return xCoordinate;
}
public void setXCoodinate(int xCoordinate) {
this.xCoordinate = xCoordinate;
}
public int getYCoordinate() {
return xCoordinate;
}
public void setYCoordinate(int yCoordinate) {
this.yCoordinate = yCoordinate;
repaint();
}
}
to add an image to the panel use something like this:
ImagePanel imagePanel = new ImagePanel();
BufferedImage image = ImageIO.read(new File("C:\\IMAGES\\"+ String.valueOf(i+1) + ".jpg"));
imagePanel.setImage(image);
Here is the code that gives me the imageIcon and where I add it to the JPanel.
Check out Darryl's Stretch Icon. It will allow the Icon to fill the entire space available to the JLabel.
Related
I have a problem using Graphics to put an image in a jPanel. I have the next code:
JFileChooser navegador = new JFileChooser();
if (navegador.showOpenDialog(null) == 0) {
try {
BufferedImage imagenAbrir = ImageIO.read(navegador.getSelectedFile());
lienzo.paintComponents(imagenAbrir.getGraphics());
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Ocurriò un error al guardar la imàgen");
}
}
The code is part of a button, the user could select an imagen from any path, but it doesn't show anything in the panel. What could be the problem?
I think you have to change you method with BufferedImage object not a Graphics object
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser navegador = new JFileChooser();
if (navegador.showOpenDialog(null) == 0) {
try {
BufferedImage imagenAbrir = ImageIO.read(navegador.getSelectedFile());
//drawPan.paintComponents(imagenAbrir.getGraphics());
drawPan.drawImage(imagenAbrir);
} catch (IOException ie) {
JOptionPane.showMessageDialog(null, "Ocurriò un error al guardar la imàgen");
}
}
}
Then, if you want to draw image, create customized JPanel class on your own.
The paintCompoent method of JComponent will be invoked automatically, every time you call repaint method in your code.
final class ImagePane extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage myImage;
public ImagePane(final BufferedImage myImage) {
this.myImage = myImage;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(240, 220);
}
public void drawImage(BufferedImage img)
{
this.myImage = img;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (myImage != null) {
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - myImage.getWidth()) / 2;
int y = (getHeight() - myImage.getHeight()) / 2;
g2d.drawImage(myImage, x, y, this);
g2d.dispose();
}
}
}
Here is full source code.
public class JFileChooserTest {
static Runnable doRun = new Runnable()
{
final class ChooseAction implements ActionListener
{
final ImagePane drawPan;
ChooseAction(final ImagePane drawPan)
{
this.drawPan = drawPan;
}
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser navegador = new JFileChooser();
if (navegador.showOpenDialog(null) == 0) {
try {
BufferedImage imagenAbrir = ImageIO.read(navegador.getSelectedFile());
//drawPan.paintComponents(imagenAbrir.getGraphics());
drawPan.drawImage(imagenAbrir);
} catch (IOException ie) {
JOptionPane.showMessageDialog(null, "Ocurriò un error al guardar la imàgen");
}
}
}
}
final class ImagePane extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage myImage;
public ImagePane(final BufferedImage myImage) {
this.myImage = myImage;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(240, 220);
}
public void drawImage(BufferedImage img)
{
this.myImage = img;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (myImage != null) {
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - myImage.getWidth()) / 2;
int y = (getHeight() - myImage.getHeight()) / 2;
g2d.drawImage(myImage, x, y, this);
g2d.dispose();
}
}
}
#Override
public void run() {
final JFrame frame = new JFrame();
//frame.setSize(new Dimension(300,400));
JPanel lienzo = new JPanel();
lienzo.setLayout(new BorderLayout());
ImagePane drawPan = new ImagePane(null);
JButton drawMe = new JButton("draw me");
lienzo.add(drawMe, BorderLayout.NORTH);
lienzo.add(drawPan, BorderLayout.CENTER);
frame.add(lienzo);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
drawMe.addActionListener(new ChooseAction(drawPan));
}
};
public static void main(String[] args)
{
SwingUtilities.invokeLater(doRun);
}
}
I hope this will help you.
The code is part of a button, the user could select an imagen from any path, but it doesn't show anything in the panel. What could be the problem?
Basically, this is not how custom painting works in Swing. Never call paintComponent or paintComponents yourself, it's not your responsibility.
What you want to do is paint the image to the component via its Graphics context
Take a look at Painting in AWT and Swing and Performing Custom Painting for more details about how painting works and how you're suppose to use it
Then take a look at How to use lables for a simple solution for displaying images
You can also have a look at How to set a background picture in JPanel. It demonstrates using a JLabel and custom component for displaying an image
So, Do you want add image on the panel in which some base image is displayed?
If so, there is some trick to achieve to do this.
I prepare two images on the internet ( I am afraid these are licensed images )
Then, now i have three buttons put on your class
JButton drawMe = new JButton("draw me");
JButton pickMe = new JButton("pick me");
JButton clearMe = new JButton("clear me");
I decided to let the DrawAction class reuse with three action commands that are a draw, pick and clear together.
drawMe.addActionListener(drawAct);
drawMe.setActionCommand("draw");
pickMe.addActionListener(drawAct);
pickMe.setActionCommand("pick");
clearMe.addActionListener(drawAct);
clearMe.setActionCommand("clear");
We'll see the ImagePane class again. If you want to add a image on a image, you should have a paintcomponent method inherited from JComponent whatever components you want to use.
The 'draw me' button is to set the base image after clearing all images in the image list in which array list of the bufferedimage class.
public void drawImage(BufferedImage img)
{
if (imageList.size() > 0) imageList.clear();
imageList.add(img);
repaint();
}
The 'pick me' button is the method that add a image to the image list.
public void addImage(BufferedImage imagenAbrir) {
imageList.add(imagenAbrir);
repaint();
}
The last one is clear button, flush and clear all image buffers in the image list.
public void clearImage() {
imageList.clear();
isClear = true;
repaint();
}
Here is my trick to clear image on the panel, it is accomplished by re-drawing canvas(jPanel at this time) with some specific color(gray).
The main method, paintComponent as following..
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(isClear)
{
Graphics2D g2d = (Graphics2D) g.create();
Rectangle2D rectangle = new Rectangle2D.Double(0,0,getWidth(),getHeight());
g2d.setPaint(Color.GRAY);
g2d.fill(rectangle);
g2d.dispose();
isClear = false;
return;
}
if (imageList.size() > 0) {
BufferedImage img = null;
for(int i = 0; i < imageList.size(); i++)
{
img = imageList.get(i);
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight() - img.getHeight()) / 2;
g2d.drawImage(img, x, y, this);
g2d.dispose();
}
}
}
Finally, you read the code below how to handle action commands along with java's component,
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("draw"))
{
JFileChooser navegador = new JFileChooser();
if (navegador.showOpenDialog(null) == 0) {
try {
BufferedImage imagenAbrir = ImageIO.read(navegador.getSelectedFile());
//drawPan.paintComponents(imagenAbrir.getGraphics());
drawPan.drawImage(imagenAbrir);
} catch (IOException ie) {
JOptionPane.showMessageDialog(null, "Ocurrio un error al guardar la imagen");
}
}
}
else if(e.getActionCommand().equals("pick"))
{
JFileChooser navegador = new JFileChooser();
if (navegador.showOpenDialog(null) == 0) {
try {
BufferedImage imagenAbrir = ImageIO.read(navegador.getSelectedFile());
//drawPan.paintComponents(imagenAbrir.getGraphics());
drawPan.addImage(imagenAbrir);
} catch (IOException ie) {
JOptionPane.showMessageDialog(null, "Ocurrio un error al guardar la imagen");
}
}
}
else if(e.getActionCommand().equals("clear"))
{
drawPan.clearImage();
}
}
As you see the code, picking a file is required every time you click both the pick or draw me button.
Full source code
package com.tobee.ui.test;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JFileChooserTest {
static Runnable doRun = new Runnable()
{
final class DrawAction implements ActionListener
{
final ImagePane drawPan;
DrawAction(final ImagePane drawPan)
{
this.drawPan = drawPan;
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
if(e.getActionCommand().equals("draw"))
{
JFileChooser navegador = new JFileChooser();
if (navegador.showOpenDialog(null) == 0) {
try {
BufferedImage imagenAbrir = ImageIO.read(navegador.getSelectedFile());
//drawPan.paintComponents(imagenAbrir.getGraphics());
drawPan.drawImage(imagenAbrir);
} catch (IOException ie) {
JOptionPane.showMessageDialog(null, "Ocurriò un error al guardar la imàgen");
}
}
}
else if(e.getActionCommand().equals("pick"))
{
JFileChooser navegador = new JFileChooser();
if (navegador.showOpenDialog(null) == 0) {
try {
BufferedImage imagenAbrir = ImageIO.read(navegador.getSelectedFile());
//drawPan.paintComponents(imagenAbrir.getGraphics());
drawPan.addImage(imagenAbrir);
} catch (IOException ie) {
JOptionPane.showMessageDialog(null, "Ocurriò un error al guardar la imàgen");
}
}
}
else if(e.getActionCommand().equals("clear"))
{
drawPan.clearImage();
}
}
}
final class ImagePane extends JPanel {
private static final long serialVersionUID = 1L;
private boolean isClear;
private List<BufferedImage> imageList;
public ImagePane()
{
imageList = new ArrayList<BufferedImage>();
isClear = false;
}
public void clearImage() {
imageList.clear();
isClear = true;
repaint();
}
public void addImage(BufferedImage imagenAbrir) {
imageList.add(imagenAbrir);
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(240, 220);
}
public void drawImage(BufferedImage img)
{
if (imageList.size() > 0) imageList.clear();
imageList.add(img);
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(isClear)
{
Graphics2D g2d = (Graphics2D) g.create();
Rectangle2D rectangle = new Rectangle2D.Double(0,0,getWidth(),getHeight());
g2d.setPaint(Color.GRAY);
g2d.fill(rectangle);
g2d.dispose();
isClear = false;
return;
}
if (imageList.size() > 0) {
BufferedImage img = null;
for(int i = 0; i < imageList.size(); i++)
{
img = imageList.get(i);
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight() - img.getHeight()) / 2;
g2d.drawImage(img, x, y, this);
g2d.dispose();
}
}
}
}
#Override
public void run() {
final JFrame frame = new JFrame();
JPanel lienzo = new JPanel();
lienzo.setLayout(new BorderLayout());
JPanel optionPan = new JPanel();
ImagePane drawPan = new ImagePane();
JButton drawMe = new JButton("draw me");
JButton pickMe = new JButton("pick me");
JButton clearMe = new JButton("clear me");
DrawAction drawAct = new DrawAction(drawPan);
optionPan.add(drawMe);
optionPan.add(pickMe);
optionPan.add(clearMe);
lienzo.add(optionPan, BorderLayout.NORTH);
lienzo.add(drawPan, BorderLayout.CENTER);
frame.add(lienzo);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
drawMe.addActionListener(drawAct);
drawMe.setActionCommand("draw");
pickMe.addActionListener(drawAct);
pickMe.setActionCommand("pick");
clearMe.addActionListener(drawAct);
clearMe.setActionCommand("clear");
}
};
public static void main(String[] args)
{
SwingUtilities.invokeLater(doRun);
}
}
I want to create a animation game by java. But it runs slowly when having image in JPanel than don't have it.
public class Multi_Paint extends JFrame implements ActionListener {
JPanel pn1 = new JPanel();
JPanel pn2 = new JPanel();
static int x=100,y=100;
Timer timer;
Multi_Paint(){
setLayout(new BorderLayout());
pn1.setBackground(Color.GREEN);
pn2.setBackground(Color.red);
pn2.setPreferredSize(new Dimension(300, 300));
add(pn1,BorderLayout.CENTER);
add(pn2,BorderLayout.WEST);
setSize(1000, 1000);
setVisible(true);
pn1.add(new DrawPanel());
pn2.add(new DrawPanel());
timer = new Timer(1, this);
timer.start();
}
public void actionPerformed(ActionEvent e) {
moveBall();
repaint();
}
void moveBall(){
x=x+10;
y=y+10;
}
public static void main(String[] args) {
new Multi_Paint();
}
}
class DrawPanel extends JPanel{
DrawPanel(){
setBorder(BorderFactory.createLineBorder(Color.black));
}
public Dimension getPreferredSize() {
return new Dimension(500,500);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int x= Multi_Paint.x;
int y= Multi_Paint.y;
//If we decline this "try" Java will run faster.
try {
BufferedImage img = ImageIO.read(new File("D:\\pict1.jpg"));
double scale = 0.5 ;
double w = scale * img.getWidth(this);
double h = scale * img.getHeight(this);
g.drawImage(img, x, y, (int) w, (int) h, this);
} catch (IOException e) {
e.printStackTrace();
}
g.fillOval(x, y, 30, 30);
}
}
As it is right now, ImageIO.read internally creates an ImageInputStream, writes the data into a new BufferedImage instance and closes the stream every single frame, which are expensive IO operations. That's why it is running slowly.
You shouldn't have any logic in your paintComponent method, or else this will slow the process down. You should rather read your image file once in your constructor and only access it in your paint method. Since your image file doesn't change over the course of the program, this is sufficient.
Something like this should work:
class DrawPanel extends JPanel {
private final BufferedImage img;
private int w;
private int h;
DrawPanel() {
setBorder(BorderFactory.createLineBorder(Color.black));
this.img = createImage("D:\\pict1.jpg");
}
private BufferedImage createImage(String path) {
BufferedImage img = null;
try {
img = ImageIO.read(new File(path));
double scale = 0.5;
this.w = (int) (scale * img.getWidth(this));
this.h = (int) (scale * img.getHeight(this));
} catch (IOException e) {
System.err.println("Could not read file with path " + path);
e.printStackTrace();
}
return img;
}
public Dimension getPreferredSize() {
return new Dimension(500,500);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int x= Multi_Paint.x;
int y= Multi_Paint.y;
// img could be null
if(this.img != null) {
g.drawImage(img, x, y, w, h, this);
}
g.fillOval(x, y, 30, 30);
}
}
I want to draw a oval image in a JLabel, using Graphics. This is my code, but a dont know about Graphics.
class imagePanel extends JLabel {
//private PlanarImage image;
private BufferedImage buffImage = null;
private void drawFingerImage(int nWidth, int nHeight, byte[] buff) {
buffImage = new BufferedImage(nWidth, nHeight, BufferedImage.TYPE_BYTE_GRAY);
buffImage.getRaster().setDataElements(0, 0, nWidth, nHeight, buff);
Graphics g = buffImage.createGraphics();
g.drawImage(buffImage, 0, 0, 140, 150, null);
g.dispose();
repaint();
}
public void paintComponent(Graphics g) {
g.drawImage(buffImage, 0, 0, this);
}
}
I have this
you need the help of setClip() method as mentioned here and here.
when it comes to code it should look like this
public class OvalImageLabel extends JLabel {
private Image image;
public OvalImageLabel(URL imageUrl) throws IOException {
image = ImageIO.read(imageUrl);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setClip(new java.awt.geom.Ellipse2D.Float(0f,0f, getWidth(),getHeight()/2));
g.drawImage(image, 0, 0, this);
}
}
and a running application that using this class
public class UsageExample extends JPanel {
public UsageExample() {
super(new BorderLayout());
OvalImageLabel l;
try {
l = new OvalImageLabel(new File("/path/to/image.png").toURI().toURL());
} catch (Exception e) {
e.printStackTrace();
return;
}
add(l, BorderLayout.CENTER);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setContentPane(new UsageExample());
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Okay, I'm using code from a book about Java, which displays 4 PNG's and 1 JPG under some text. They provide me with code and the images are downloadable from the site, which i downloaded. To upload the images to eclipse, I made a source folder in my project to keep the images. I then uploaded my images to the "images" source folder by doing New>File>2DGraphicsTest>LinkToFileSystem> and then i selected my image. But for some reason, when i run the following code i just get the text that goes above my pictures....
My question is, how do i upload the images properly so that the loadImage(image) thing gets it?
Code:
import java.awt.*;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class ImageTest extends JFrame {
public static void main(String[] args) {
DisplayMode displayMode;
if (args.length == 3) {
displayMode = new DisplayMode(
Integer.parseInt(args[0]),
Integer.parseInt(args[1]),
Integer.parseInt(args[2]),
DisplayMode.REFRESH_RATE_UNKNOWN);
}
else {
displayMode = new DisplayMode(800, 600, 16,
DisplayMode.REFRESH_RATE_UNKNOWN);
}
ImageTest test = new ImageTest();
test.run(displayMode);
}
private static final int FONT_SIZE = 24;
private static final long DEMO_TIME = 10000;
private SimpleScreenManager screen;
private Image bgImage;
private Image opaqueImage;
private Image transparentImage;
private Image translucentImage;
private Image antiAliasedImage;
private boolean imagesLoaded;
public void run(DisplayMode displayMode) {
setBackground(Color.blue);
setForeground(Color.black);
setFont(new Font("Consolas", Font.PLAIN, FONT_SIZE));
imagesLoaded = false;
screen = new SimpleScreenManager();
try {
screen.setFullScreen(displayMode, this);
loadImages();
try {
Thread.sleep(DEMO_TIME);
}
catch (InterruptedException ex) { }
}
finally {
screen.restoreScreen();
}
}
public void loadImages() {
bgImage = loadImage("images/background.jpg");
opaqueImage = loadImage("images/opaque.png");
transparentImage = loadImage("images/transparent.png");
translucentImage = loadImage("images/translucent.png");
antiAliasedImage = loadImage("images/antialiased.png");
imagesLoaded = true;
// signal to AWT to repaint this window
repaint();
}
private Image loadImage(String fileName) {
return new ImageIcon(fileName).getImage();
}
public void paint(Graphics g) {
// set text anti-aliasing
if (g instanceof Graphics2D) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
// draw images
if (imagesLoaded) {
g.drawImage(bgImage, 0, 0, null);
drawImage(g, opaqueImage, 0, 0, "Opaque");
drawImage(g, transparentImage, 320, 0, "Transparent");
drawImage(g, translucentImage, 0, 300, "Translucent");
drawImage(g, antiAliasedImage, 320, 300,
"Translucent (Anti-Aliased)");
}
else {
g.drawString("Loading Images...", 5, FONT_SIZE);
}
}
public void drawImage(Graphics g, Image image, int x, int y,
String caption)
{
g.drawImage(image, x, y, null);
g.drawString(caption, x + 5, y + FONT_SIZE +
image.getHeight(null));
}
}
I am trying to scale a screenshot taken by:
robot.createScreenCapture(SCREEN_RECT);
Im trying to get it down to an image that is 600X400 and fits into a JFrame that is 600X400
My program is using a swing worker to create an video out of each picture, or frames. The frames have a delay of 200ms per each. the image when told to rescale just shows the original image at the original dimensions. Does anyone know how to fix this, or should I just give up on the resize-ing?
#SuppressWarnings("serial")
public class temporaryShit extends JPanel
{
private static final int width = 600;
private static final int height = 400;
private JLabel displayedLabel = new JLabel();
public temporaryShit()
{
setLayout(new BorderLayout());
add(displayedLabel);
try {
MySwingWorker mySwingWorker = new MySwingWorker();
mySwingWorker.execute();
} catch (AWTException e) {
}
}
public void setLabelIcon(Icon icon) {
displayedLabel.setIcon(icon);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
private class MySwingWorker extends SwingWorker<Void, Icon>
{
private final Rectangle SCREEN_RECT = new Rectangle(0, 0, width, height);
private long delay = 200;
private Robot robot = null;
public MySwingWorker() throws AWTException
{
robot = new Robot();
}
#Override
protected Void doInBackground() throws Exception
{
Timer utilTimer = new Timer();
TimerTask task = new TimerTask()
{
#Override
public void run()
{
BufferedImage capturedImage = captureScreen();
publish(new ImageIcon(capturedImage));
}
};
utilTimer.scheduleAtFixedRate(task, delay, delay);
return null;
}
#Override
protected void process(List<Icon> chunks)
{
for (Icon icon : chunks)
{
setLabelIcon(icon);
}
}
private BufferedImage captureScreen()
{
BufferedImage img = robot.createScreenCapture(SCREEN_RECT);
return createResizedImage(img, width, height);
}
public BufferedImage createResizedImage(Image original, int width, int height)
{
BufferedImage scaledBI = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = scaledBI.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(original, 0, 0, width, height, null);
g.dispose();
return scaledBI;
}
}
private static void createAndShowGui()
{
temporaryShit mainPanel = new temporaryShit();
JFrame frame = new JFrame("SwingWorker Eg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGui();
}
});
}
}
You already have a new image with specified size - scaled, which you can use for rendering.
Here is a simple example:
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
class TestBrightness {
public static void main(String args[]) {
try {
URL imageUrl = new URL(
"http://duke.kenai.com/comfyChair/ComfyChairRadSmall.jpg");
BufferedImage ioImage = ImageIO.read(imageUrl);
JPanel panel = new JPanel();
Image scaledImg = ioImage.getScaledInstance(ioImage.getWidth() / 2,
ioImage.getHeight() / 2, Image.SCALE_SMOOTH);
panel.add(new JLabel(new ImageIcon(ioImage)));
panel.add(new JLabel(new ImageIcon(scaledImg)));
JOptionPane.showMessageDialog(null, panel, "100% vs 50%",
JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Failure",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
}
As a side note, there are many ways to scale an image and Image.getScaledInstance() may not be the best. You may be interested to take a look at The Perils of Image.getScaledInstance() for some details on Image.getScaledInstance()
EDIT: question update
Last question update removed all the details regarding getScaledInstance and invalidated this answer. getScaledInstance is a very slow method and it is also asynchronous. Try this method to get a resized image:
public static BufferedImage createResizedImage(Image original, int width,
int height) {
BufferedImage scaledBI = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = scaledBI.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(original, 0, 0, width, height, null);
g.dispose();
return scaledBI;
}
You may want to change rendering hints for better quality.
For a nicer and more complete image scaler take a look at getFasterScaledInstance() from Filthy Rich Clients book.
EDIT : last question update with posted code and SwingWorker
The implementation of SwingWorker is not correct. doInBackground() schedules java.Utils.Timer. This timer handles all updates, while the actual SwingWorker worker thread ends. All updates from the timer are fired not on Event Dispatch Thread. It may not be safe to allocate ImageIcon not on EDT. And for sure it is not safe to update UI, ie calling setLabelIcon() not on EDT. See Concurrency in Swing tutorial for details.
You can add while loop and Thread.sleep in doInBackground() and remove the timer. Alternatively, Swing timer may be more suitable for this case. Here is an example:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class DemoRobotPanel extends JPanel{
private static final long serialVersionUID = 1L;
private Image image;
private Robot robot;
private Rectangle CAPTURE_RECT;
private int TIMER_DELAY = 1000;
private int desiredWidth = 600;
private int desiredHeight = 400;
public DemoRobotPanel() {
CAPTURE_RECT = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
try {
robot = new Robot();
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
BufferedImage img = robot.createScreenCapture(CAPTURE_RECT);
setImage(img);
} catch (HeadlessException e) {
e.printStackTrace();
}
}
};
Timer timer = new Timer(TIMER_DELAY, taskPerformer);
timer.start();
} catch (AWTException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(desiredWidth, desiredHeight);
}
public void setImage(Image image) {
this.image = image;
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null)
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
private static void createAndShowGui() {
final DemoRobotPanel panel = new DemoRobotPanel();
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Try this:
public BufferedImage resize(BufferedImage bufferedImage, int resizeWidth, int resizeHeight) {
// Create new (blank) image of required (scaled) size
BufferedImage scaledImage = new BufferedImage(resizeWidth, resizeHeight, BufferedImage.TYPE_INT_ARGB);
// Paint scaled version of image to new image
Graphics2D graphics2D = scaledImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(bufferedImage, 0, 0, resizeWidth, resizeHeight, null);
graphics2D.dispose();
return scaledImage;
}
You may want to try different RenderingHints.