Image is not drawing on top left of panel - java

When i load image ,it do not load at upper left (if the image is large to be fit on window size).This is because i diminish its size as shown in code. Although i am giving its coordinate value 0,0 it is not drawing at that position.
import javax.swing.*;
import javax.imageio.ImageIO;
import java.io.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class photo extends JFrame
{
Dimension screenwidth=getToolkit().getScreenSize();
int mx=(int)screenwidth.getWidth();
int my=(int)screenwidth.getHeight();
BufferedImage picture1;
JLabel label3;
int neww;
int newh;
public photo() {
JFrame f = new JFrame("Image Editor v1.0");
f.setLayout(null);
try{
File file=new File("e:\\8.jpg");
picture1=ImageIO.read(file);
}catch(Exception e)
{
}
JPanel panel2 = new JPanel();
panel2.setLayout(null);
panel2.setBounds(101,20,mx-100,my-20);
f.add(panel2);
label3 = new JLabel("");
label3.setBounds(110,30,mx-110,my-30);
panel2.add(label3);
f.setExtendedState(Frame.MAXIMIZED_BOTH);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BufferedImage bi = null;
if(picture1.getWidth()>mx-110 ||picture1.getHeight()>my-30 )
{
neww= (int) Math.round(picture1.getWidth() * 0.25);
newh = (int) Math.round(picture1.getHeight() *0.25);
}
else
{
neww=picture1.getWidth();
newh=picture1.getHeight();
}
bi = new BufferedImage(neww,newh,BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(picture1,0,0,neww,newh,0,0,picture1.getWidth(),picture1.getHeight(), null);
label3.setIcon(new ImageIcon(bi));
}
public static void main(String[] args)
{
new photo();
}
}

You could add g2d.translate(0, 0); between g2d.addRenderingHints and g2d.drawImage and try it.
EDIT
So if you want the image to be at 101 px and 20 px, you should label3.setBounds(0,0,neww,newh); after label3.setIcon(new ImageIcon(bi)); instead of the current. I think this shall work as I have just tested.

Related

Create Image from JCanvas (Java) [duplicate]

How do I obtain a java.awt.Image of a JFrame?
I want to obtain a screen shot of a JFrame (for later use within my application). This is presently accomplished using the robot to take a screen shot specifying the coordinates and dimensions of the JFrame involved.
However, I believe that there is a better way: Swing components, by default, render themselves as images into a double buffer prior to painting themselves onto the screen.
Is there a way to obtain these images from the component?
ComponentImageCapture.java
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Image;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.imageio.ImageIO;
import java.io.File;
/**
Create a screenshot of a component.
#author Andrew Thompson
*/
class ComponentImageCapture {
static final String HELP =
"Type Ctrl-0 to get a screenshot of the current GUI.\n" +
"The screenshot will be saved to the current " +
"directory as 'screenshot.png'.";
public static BufferedImage getScreenShot(
Component component) {
BufferedImage image = new BufferedImage(
component.getWidth(),
component.getHeight(),
BufferedImage.TYPE_INT_RGB
);
// call the Component's paint method, using
// the Graphics object of the image.
component.paint( image.getGraphics() ); // alternately use .printAll(..)
return image;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
final JFrame f = new JFrame("Test Screenshot");
JMenuItem screenshot =
new JMenuItem("Screenshot");
screenshot.setAccelerator(
KeyStroke.getKeyStroke(
KeyEvent.VK_0,
InputEvent.CTRL_DOWN_MASK
));
screenshot.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae) {
BufferedImage img = getScreenShot(
f.getContentPane() );
JOptionPane.showMessageDialog(
null,
new JLabel(
new ImageIcon(
img.getScaledInstance(
img.getWidth(null)/2,
img.getHeight(null)/2,
Image.SCALE_SMOOTH )
)));
try {
// write the image as a PNG
ImageIO.write(
img,
"png",
new File("screenshot.png"));
} catch(Exception e) {
e.printStackTrace();
}
}
} );
JMenu menu = new JMenu("Other");
menu.add(screenshot);
JMenuBar mb = new JMenuBar();
mb.add(menu);
f.setJMenuBar(mb);
JPanel p = new JPanel( new BorderLayout(5,5) );
p.setBorder( new TitledBorder("Main GUI") );
p.add( new JScrollPane(new JTree()),
BorderLayout.WEST );
p.add( new JScrollPane( new JTextArea(HELP,10,30) ),
BorderLayout.CENTER );
f.setContentPane( p );
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
Screen shot
See also
The code shown above presumes the component has been realized on-screen, prior to rendering.
Rob Camick shows how to paint an unrealized component in the Screen Image class.
Another thread that might be of relevance, is Render JLabel without 1st displaying, particularly the 'one line fix' by Darryl Burke.
LabelRenderTest.java
Here is an updated variant of the code shown on the second link.
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class LabelRenderTest {
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
String title = "<html><body style='width: 200px; padding: 5px;'>"
+ "<h1>Do U C Me?</h1>"
+ "Here is a long string that will wrap. "
+ "The effect we want is a multi-line label.";
JFrame f = new JFrame("Label Render Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BufferedImage image = new BufferedImage(
400,
300,
BufferedImage.TYPE_INT_RGB);
Graphics2D imageGraphics = image.createGraphics();
GradientPaint gp = new GradientPaint(
20f,
20f,
Color.red,
380f,
280f,
Color.orange);
imageGraphics.setPaint(gp);
imageGraphics.fillRect(0, 0, 400, 300);
JLabel textLabel = new JLabel(title);
textLabel.setSize(textLabel.getPreferredSize());
Dimension d = textLabel.getPreferredSize();
BufferedImage bi = new BufferedImage(
d.width,
d.height,
BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.setColor(new Color(255, 255, 255, 128));
g.fillRoundRect(
0,
0,
bi.getWidth(f),
bi.getHeight(f),
15,
10);
g.setColor(Color.black);
textLabel.paint(g);
Graphics g2 = image.getGraphics();
g2.drawImage(bi, 20, 20, f);
ImageIcon ii = new ImageIcon(image);
JLabel imageLabel = new JLabel(ii);
f.getContentPane().add(imageLabel);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}
Screen shot

Colorize a picture in java

I would like, for a java project, to change the color of a hair modelisation (to change hair color) with shadows and reflects...
In fact, I wondered if there's a class which can change the color of a picture with a RGB code. If this can help you, here's the picture I need to colorize :
I assume that the question targeted NOT at blindly replacing certain pixels with a certain (fixed) color, but at really "dyeing" the image. Once I wrote a sample class showing how this could be done:
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
import javax.imageio.*;
class DyeImage
{
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try
{
new DyeImage();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public DyeImage() throws Exception
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BufferedImage image = ImageIO.read(new File("DRVpH.png"));
JPanel panel = new JPanel(new GridLayout(1,0));
panel.add(new JLabel(new ImageIcon(image)));
panel.add(new JLabel(new ImageIcon(dye(image, new Color(255,0,0,128)))));
panel.add(new JLabel(new ImageIcon(dye(image, new Color(255,0,0,32)))));
panel.add(new JLabel(new ImageIcon(dye(image, new Color(0,128,0,32)))));
panel.add(new JLabel(new ImageIcon(dye(image, new Color(0,0,255,32)))));
f.getContentPane().add(panel);
f.pack();
f.setVisible(true);
}
private static BufferedImage dye(BufferedImage image, Color color)
{
int w = image.getWidth();
int h = image.getHeight();
BufferedImage dyed = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = dyed.createGraphics();
g.drawImage(image, 0,0, null);
g.setComposite(AlphaComposite.SrcAtop);
g.setColor(color);
g.fillRect(0,0,w,h);
g.dispose();
return dyed;
}
}
The result with the given image and different dyeing colors will look like this:

Drawing directly on glasspane: not working

I am developing an app using Swing. While user interact with the app, help data may become available in a closed section of the screen, and I'd like to draw a small arrow pointing to that section when this happens.
To do this, I extended a JPanel and added it as the glasspane of the app jframe. The name of the custom glass pane class is AlertGlassPane.
The AlertGlassPane do this: waits until new help data is available. When this happens and the help section is closed, it finds the position of the help section on the screen and then draws an animated arrow at its side.
To draw the arrow I extended the method paintComponent of the glass pane.
To animate the arrow I created a small thread that loop every 100 ms, calling repaint on the glass pane.
The problem: Java ignores my drawing... if a trigger the start of the animation and stand still, nothing happens. No drawing is shown on the app.
I know that the loop is running and paintComponent is being called, but the custom paint is not taking effect.
But if I move the mouse over the region where the arrow should be rendered, it does! But just when the mouse is moving. If a stop move the mouse, the animation stops too, and the arrow freezes on the last position before the mouse stop (or leaves the area).
I tried a lot of things (as set the clip region of the drawing, for example), but nothing seems to work. The only thing that works was when I called by mistake repaint from inside the paintComponent.
At this moment I'm looking for a way to comunicate to the rendering system that a givem region of my glasspane needs to be repainted (repaint(x, y, w, h) didn't work...). Maybe moving the custom rendering to a JLabel and then adding this label to the glasspane? I don't like this approach...
I'll try to clean up the code before post a snippet here. Would it help?
Thanks in advance!
snnipet:
package br.com.r4j.test;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.JTextComponent;
/**
*
* #author
*/
public class TestGlassPaneAnimation extends JPanel
{
private static TestGlassPaneAnimation gvp = new TestGlassPaneAnimation();
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
JFrame f = new JFrame("Anitest in glass");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//f.setResizable(false);
f.setLayout(new GridLayout(5, 3));
f.add(new JLabel("First Name :"));
f.add(new JTextField(20));
f.add(new JLabel("Last Name :"));
f.add(new JTextField(20));
f.add(new JLabel("Phone Number :"));
f.add(new JTextField(20));
f.add(new JLabel("Email:"));
f.add(new JTextField(20));
f.add(new JLabel("Address :"));
f.add(new JTextField(20));
JButton btnStart = new JButton("Click me, please!");
f.add(btnStart);
btnStart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
gvp.startAnimation();
}
});
f.setGlassPane(gvp);
f.pack();
f.setVisible(true);
gvp.setVisible(true);
}
});
}
private BufferedImage icon;
private boolean animate = false;
private long timeStart = 0;
private Thread thrLastActive = null;
public TestGlassPaneAnimation()
{
setLayout(null);//this is the exception to the rule case a layoutmanager might make setting Jlabel co-ords harder
setOpaque(false);
Icon icon1 = UIManager.getIcon("OptionPane.warningIcon");
int imgW = icon1.getIconWidth();
int imgH = icon1.getIconHeight();
this.icon = ImageUtilities.getBufferedImageOfIcon(icon1, imgW, imgH);
this.animate = false;
}
public void startAnimation()
{
this.animate = true;
this.timeStart = (new Date()).getTime();
if (this.thrLastActive != null)
this.thrLastActive.interrupt();
this.thrLastActive = new Thread(new Runnable()
{
public void run()
{
try
{
while (true)
{
// int x = 250, y = 250;
// int width = 60, height = 60;
Thread.currentThread().sleep(100);
// frmRoot.invalidate();
// repaint(x, y, width, height);
repaint(new Rectangle(x, y, width, height));
// repaint(new Rectangle(10, 10, 2000, 2000));
// repaint();
// paintComponent(getGraphics());
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
this.thrLastActive.start();
}
protected void paintComponent(Graphics g)
{
try
{
// enables anti-aliasing
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
java.awt.Composite composite = g2.getComposite();
System.err.println("b1: " + g.getClipBounds());
if (this.animate)
{
long timeSpent = (new Date()).getTime() - timeStart;
int x = 10, y = 150;
int width = 60, height = 60;
float maxAlpha = 0.8f;
x += (-100*Math.sin(5*2*Math.PI*timeSpent/10000)+50)/15;
System.err.println("painting::x: " + x + ", y: " + y + ", sin: " + (Math.sin(6*2*Math.PI*timeSpent/10000)));
// g.setClip(x-10, y-10, width, height);
System.err.println("b2: " + g.getClipBounds());
AlphaComposite alpha2 = AlphaComposite.SrcOver.derive(maxAlpha);
g2.setComposite(alpha2);
g2.drawImage(this.icon, x, y, null);
g2.setComposite(composite);
g2.setComposite(composite);
}
}
catch (Throwable e)
{
System.err.println("Errr!");
e.printStackTrace();
}
}
}
class ImageUtilities {
public static BufferedImage resize(BufferedImage image, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return bi;
}
public static BufferedImage getBufferedImageOfIcon(Icon icon, int imgW, int imgH) {
BufferedImage img = new BufferedImage(imgW, imgH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();
return img;
}
}
Hmm not sure exactly whats going on with the snippet you gave but as it looks like it was taken from mine I wrote another example (I had to change a 1 or 2 lines of code in showWarningIcon(Component c) and refreshLocations() methods but nothing major:
If anything except david is typed and the button (click me, please) clicked it will show this:
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class TestGlassPaneAnimation {
private static GlassValidationPane gvp = new GlassValidationPane();
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Anitest in glass");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//f.setResizable(false);
f.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.HORIZONTAL;
gc.weightx = 1;
gc.weighty = 1;
gc.insets = new Insets(15, 15, 15, 15);//give some space so icon doesnt cover components when shown
gc.gridx = 0;
gc.gridy = 0;
f.add(new JLabel("First Name:"), gc);
final JTextField jtf = new JTextField(20);
gc.gridx = 1;
f.add(jtf, gc);
gc.gridx = 0;
gc.gridy = 1;
f.add(new JLabel("Surname:"), gc);
final JTextField jtf2 = new JTextField(20);
gc.gridx = 1;
f.add(jtf2, gc);
JButton btnStart = new JButton("Click me, please!");
gc.gridx = 2;
f.add(btnStart, gc);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!jtf.getText().equalsIgnoreCase("david")) {
gvp.showWarningIcon(jtf);
}
}
});
f.addComponentListener(new ComponentAdapter() {//so wjen frame is resized icons follow
#Override
public void componentResized(ComponentEvent ce) {
super.componentResized(ce);
gvp.refreshLocations();
}
});
f.setGlassPane(gvp);
f.pack();
f.setVisible(true);
gvp.setVisible(true);
}
});
}
}
class GlassValidationPane extends JPanel {
private HashMap<Component, JLabel> warningLabels = new HashMap<>();
private ImageIcon warningIcon;
public GlassValidationPane() {
setLayout(null);//this is the exception to the rule case a layoutmanager might make setting Jlabel co-ords harder
setOpaque(false);
Icon icon = UIManager.getIcon("OptionPane.warningIcon");
int imgW = icon.getIconWidth();
int imgH = icon.getIconHeight();
BufferedImage img = ImageUtilities.getBufferedImageOfIcon(icon, imgW, imgH);
warningIcon = new ImageIcon(ImageUtilities.resize(img, 24, 24));
}
void showWarningIcon(Component c) {
if (warningLabels.containsKey(c)) {
return;
}
JLabel label = new JLabel();
label.setIcon(warningIcon);
//int x=c.getX();//this will make it insode the component
int x = c.getX() - warningIcon.getIconWidth();//this makes it appear outside/next to component if space
int y = c.getY();
label.setBounds(x, y, warningIcon.getIconWidth(), warningIcon.getIconHeight());
add(label);
revalidate();
repaint();
warningLabels.put(c, label);
}
public void removeWarningIcon(Component c) {
for (Map.Entry<Component, JLabel> entry : warningLabels.entrySet()) {
Component component = entry.getKey();
JLabel jLabel = entry.getValue();
if (component == c) {
remove(jLabel);
revalidate();
repaint();
break;
}
}
warningLabels.remove(c);
}
public void refreshLocations() {
for (Map.Entry<Component, JLabel> entry : warningLabels.entrySet()) {
Component c = entry.getKey();
JLabel label = entry.getValue();
//int x=c.getX();//this will make it insode the component
int x = c.getX() - label.getIcon().getIconWidth();//this makes it appear outside/next to component
int y = c.getY();
label.setBounds(x, y, label.getIcon().getIconWidth(), label.getIcon().getIconHeight());
revalidate();
repaint();
}
}
}
class ImageUtilities {
public static BufferedImage resize(BufferedImage image, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return bi;
}
public static BufferedImage getBufferedImageOfIcon(Icon icon, int imgW, int imgH) {
BufferedImage img = new BufferedImage(imgW, imgH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();
return img;
}
}
If you are looking for a more mature library have a look at JXLayer - Validation Overlays and Validation overlays using glass pane.
Also might want to have a read here which shows many ways of validating a textfields data (other than button press) like DocumentFilter and InputVerifier etc.

Set Color as int value for use in setRGB(int x, int y, int rgb) method? -- Java

Any other errors aside, I need a way of converting my Color grayScale into an int. When I plug in the Color, I get an error. setRGB method takes an x, a y, and an rgb int as parameters. How do I change my Color into an int?
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
public class Picture{
Container content;
BufferedImage image, image2;
public Picture(String filename) {
File f = new File(filename);
//assume file is the image file
try {
image = ImageIO.read(f);
}
catch (IOException e) {
System.out.println("Invalid image file: " + filename);
System.exit(0);
}
}
public void show() {
final int width = image.getWidth();
final int height = image.getHeight();
JFrame frame = new JFrame("Edit Picture");
//set frame title, set it visible, etc
content = frame.getContentPane();
content.setPreferredSize(new Dimension(width, height));
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add a menubar on the frame with a single option: saving the image
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
JMenuItem saveAction = new JMenuItem("Save");
fileMenu.add(saveAction);
JMenuItem grayScale = new JMenuItem("Grayscale");
fileMenu.add(grayScale);
grayScale.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
grayscale(width, height);
}
});
//add the image to the frame
ImageIcon icon = new ImageIcon(image);
frame.setContentPane(new JLabel(icon));
//paint the frame
frame.setVisible(true);
frame.repaint();
}
public void grayscale(int width, int height) {
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
Color color = new Color(image.getRGB(i, j));
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
int rGray = red*(1/3);
int gGray = green*(2/3);
int bGray = blue*(1/10);
Color grayScale = new Color(rGray, gGray, bGray);
image.setRGB(i,j, grayScale);
}
}
show();
}
public static void main(String[] args) {
Picture p = new Picture(args[0]);
p.show();
}
}
As per comment by trashgod.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.image.*;
public class Picture{
Container content;
BufferedImage image;
BufferedImage image2;
public Picture(BufferedImage image) {
this.image = image;
grayscale();
}
public void show() {
JFrame frame = new JFrame("Edit Picture");
//set frame title, set it visible, etc
content = frame.getContentPane();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add the image to the frame
ImageIcon icon = new ImageIcon(image2);
frame.setContentPane(new JLabel(icon));
frame.pack();
//paint the frame
frame.setVisible(true);
}
public void grayscale() {
// create a grayscale image the same size
image2 = new BufferedImage(
image.getWidth(),
image.getHeight(),
BufferedImage.TYPE_BYTE_GRAY);
// convert the original colored image to grayscale
ColorConvertOp op = new ColorConvertOp(
image.getColorModel().getColorSpace(),
image2.getColorModel().getColorSpace(),null);
op.filter(image,image2);
show();
}
public static void main(String[] args) {
int size = 120;
int pad = 10;
BufferedImage bi = new BufferedImage(
size,
size,
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0,0,size,size);
g.setColor(Color.YELLOW);
g.fillOval(pad,pad,size-(2*pad),size-(2*pad));
g.dispose();
Picture p = new Picture(bi);
p.show();
}
}
image.setRGB(i, j, grayScale.getRGB());
Take a look at what values (1/3), (2/3), and (1/10) actually have, then note that you are multiplying your red, green, and blue values by those numbers.
The color is an Object. An rgb is an int. Use colorName.getRGB() to get the integer RGB value of that color.

Swing: Obtain Image of JFrame

How do I obtain a java.awt.Image of a JFrame?
I want to obtain a screen shot of a JFrame (for later use within my application). This is presently accomplished using the robot to take a screen shot specifying the coordinates and dimensions of the JFrame involved.
However, I believe that there is a better way: Swing components, by default, render themselves as images into a double buffer prior to painting themselves onto the screen.
Is there a way to obtain these images from the component?
ComponentImageCapture.java
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Image;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.imageio.ImageIO;
import java.io.File;
/**
Create a screenshot of a component.
#author Andrew Thompson
*/
class ComponentImageCapture {
static final String HELP =
"Type Ctrl-0 to get a screenshot of the current GUI.\n" +
"The screenshot will be saved to the current " +
"directory as 'screenshot.png'.";
public static BufferedImage getScreenShot(
Component component) {
BufferedImage image = new BufferedImage(
component.getWidth(),
component.getHeight(),
BufferedImage.TYPE_INT_RGB
);
// call the Component's paint method, using
// the Graphics object of the image.
component.paint( image.getGraphics() ); // alternately use .printAll(..)
return image;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
final JFrame f = new JFrame("Test Screenshot");
JMenuItem screenshot =
new JMenuItem("Screenshot");
screenshot.setAccelerator(
KeyStroke.getKeyStroke(
KeyEvent.VK_0,
InputEvent.CTRL_DOWN_MASK
));
screenshot.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae) {
BufferedImage img = getScreenShot(
f.getContentPane() );
JOptionPane.showMessageDialog(
null,
new JLabel(
new ImageIcon(
img.getScaledInstance(
img.getWidth(null)/2,
img.getHeight(null)/2,
Image.SCALE_SMOOTH )
)));
try {
// write the image as a PNG
ImageIO.write(
img,
"png",
new File("screenshot.png"));
} catch(Exception e) {
e.printStackTrace();
}
}
} );
JMenu menu = new JMenu("Other");
menu.add(screenshot);
JMenuBar mb = new JMenuBar();
mb.add(menu);
f.setJMenuBar(mb);
JPanel p = new JPanel( new BorderLayout(5,5) );
p.setBorder( new TitledBorder("Main GUI") );
p.add( new JScrollPane(new JTree()),
BorderLayout.WEST );
p.add( new JScrollPane( new JTextArea(HELP,10,30) ),
BorderLayout.CENTER );
f.setContentPane( p );
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
Screen shot
See also
The code shown above presumes the component has been realized on-screen, prior to rendering.
Rob Camick shows how to paint an unrealized component in the Screen Image class.
Another thread that might be of relevance, is Render JLabel without 1st displaying, particularly the 'one line fix' by Darryl Burke.
LabelRenderTest.java
Here is an updated variant of the code shown on the second link.
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class LabelRenderTest {
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
String title = "<html><body style='width: 200px; padding: 5px;'>"
+ "<h1>Do U C Me?</h1>"
+ "Here is a long string that will wrap. "
+ "The effect we want is a multi-line label.";
JFrame f = new JFrame("Label Render Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BufferedImage image = new BufferedImage(
400,
300,
BufferedImage.TYPE_INT_RGB);
Graphics2D imageGraphics = image.createGraphics();
GradientPaint gp = new GradientPaint(
20f,
20f,
Color.red,
380f,
280f,
Color.orange);
imageGraphics.setPaint(gp);
imageGraphics.fillRect(0, 0, 400, 300);
JLabel textLabel = new JLabel(title);
textLabel.setSize(textLabel.getPreferredSize());
Dimension d = textLabel.getPreferredSize();
BufferedImage bi = new BufferedImage(
d.width,
d.height,
BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.setColor(new Color(255, 255, 255, 128));
g.fillRoundRect(
0,
0,
bi.getWidth(f),
bi.getHeight(f),
15,
10);
g.setColor(Color.black);
textLabel.paint(g);
Graphics g2 = image.getGraphics();
g2.drawImage(bi, 20, 20, f);
ImageIcon ii = new ImageIcon(image);
JLabel imageLabel = new JLabel(ii);
f.getContentPane().add(imageLabel);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}
Screen shot

Categories

Resources