How to save image drawn on a JPanel?
Posted
by swift
on Stack Overflow
See other posts from Stack Overflow
or by swift
Published on 2010-04-15T05:41:25Z
Indexed on
2010/04/15
5:43 UTC
Read the original article
Hit count: 402
I have a panel with transparent background which i use to draw an image. now problem here is when i draw anything on panel and save the image as a JPEG file its saving the image with black background but i want it to be saved as same, as i draw on the panel. what should be done for this? plz guide me
j Client.java
public class Client extends Thread
{
static DatagramSocket datasocket;
static DatagramSocket socket;
Point point;
Whiteboard board;
Virtualboard virtualboard;
JLayeredPane layerpane;
BufferedImage image;
public Client(DatagramSocket datasocket)
{
Client.datasocket=datasocket;
}
//This function is responsible to connect to the server
public static void connect()
{
try
{
socket=new DatagramSocket (9000); //client connection socket port= 9000
datasocket=new DatagramSocket (9005); //client data socket port= 9002
ByteArrayOutputStream baos=new ByteArrayOutputStream();
DataOutputStream dos=new DataOutputStream(baos);
//this is to tell server that this is a connection request
dos.writeChar('c');
dos.close();
byte[]data=baos.toByteArray();
//Server IP address
InetAddress ip=InetAddress.getByName("10.123.97.154");
//create the UDP packet
DatagramPacket packet=new DatagramPacket(data, data.length,ip , 8000);
socket.send(packet);
Client client=new Client(datasocket);
client.createFrame();
client.run();
}
catch(Exception e)
{
e.printStackTrace();
}
}
//This function is to create the JFrame
public void createFrame()
{
JFrame frame=new JFrame("Whiteboard");
frame.setVisible(true);
frame.setBackground(Color.black);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(680,501);
frame.addWindowListener(new WindowAdapter()
{
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e)
{
close();
}
});
layerpane=frame.getLayeredPane();
board= new Whiteboard(datasocket);
image = new BufferedImage(590,463, BufferedImage.TYPE_INT_ARGB);
board.setBounds(74,2,590,463);
board.setImage(image);
virtualboard=new Virtualboard();
virtualboard.setImage(image);
virtualboard.setBounds(74,2,590,463);
layerpane.add(virtualboard,new Integer(2));//Panel where remote user draws
layerpane.add(board,new Integer(3));
layerpane.add(board.colourButtons(),new Integer(1));
layerpane.add(board.shapeButtons(),new Integer(0));
//frame.add(paper.addButtons(),BorderLayout.WEST);
}
/*
* This function is overridden from the thread class
* This function listens for incoming packets from the server
* which contains the points drawn by the other client
*/
public void run ()
{
while (true)
{
try
{
byte[] buffer = new byte[512];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
datasocket.receive(packet);
InputStream in=new ByteArrayInputStream(packet.getData(), packet.getOffset(),packet.getLength());
DataInputStream din=new DataInputStream(in);
int x=din.readInt();
int y=din.readInt();
String varname=din.readLine();
String var[]=varname.split("-",4);
point=new Point(x,y);
virtualboard.addPoint(point, var[0], var[1],var[2],var[3]);
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
//This function is to broadcast the newly drawn point to the server
public void broadcast (Point p,String varname,String shape,String event, String color)
{
try
{
ByteArrayOutputStream baos=new ByteArrayOutputStream();
DataOutputStream dos=new DataOutputStream(baos);
dos.writeInt(p.x);
dos.writeInt(p.y);
dos.writeBytes(varname);
dos.writeBytes("-");
dos.writeBytes(shape);
dos.writeBytes("-");
dos.writeBytes(event);
dos.writeBytes("-");
dos.writeBytes(color);
dos.close();
byte[]data=baos.toByteArray();
InetAddress ip=InetAddress.getByName("10.123.97.154");
DatagramPacket packet=new DatagramPacket(data, data.length,ip , 8002);
datasocket.send(packet);
}
catch (Exception e)
{
e.printStackTrace();
}
}
//This function is to close the client's connection with the server
public void close()
{
try
{
ByteArrayOutputStream baos=new ByteArrayOutputStream();
DataOutputStream dos=new DataOutputStream(baos);
//This is to tell server that this is request to remove the client
dos.writeChar('r');
dos.close();
byte[]data=baos.toByteArray();
//Server IP address
InetAddress ip=InetAddress.getByName("10.123.97.154");
DatagramPacket packet=new DatagramPacket(data, data.length,ip , 8000);
socket.send(packet);
System.out.println("closed");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
connect();
}
}
Whiteboard.java
class Whiteboard extends JPanel implements MouseListener,MouseMotionListener,ActionListener,KeyListener
{
BufferedImage image;
Boolean tooltip=false;
int post;
String shape;
String selectedcolor="black";
Color color=Color.black;
//Color color=Color.white;
Point start;
Point end;
Point mp;
Point tip;
int keycode;
String fillshape;
Point fillstart=new Point();
Point fillend=new Point();
int noofside;
Button r=new Button("rect");
Button rectangle=new Button("rect");
Button line=new Button("line");
Button roundrect=new Button("roundrect");
Button polygon=new Button("poly");
Button text=new Button("text");
JButton save=new JButton("Save");
Button elipse=new Button("elipse");
ImageIcon fillicon=new ImageIcon("images/fill.jpg");
JButton fill=new JButton(fillicon);
ImageIcon erasericon=new ImageIcon("images/eraser.gif");
JButton erase=new JButton(erasericon);
JButton[] colourbutton=new JButton[28];
String selected;
Point label;
String key="";
int ex,ey;//eraser
DatagramSocket dataSocket;
JButton button = new JButton("test");
Client client;
Boolean first;
int w,h;
public Whiteboard(DatagramSocket dataSocket)
{
try
{
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
}
catch (Exception e)
{
e.printStackTrace();
}
setLayout(null);
setOpaque(false);
setBackground(new Color(237,237,237));
this.dataSocket=dataSocket;
client=new Client(dataSocket);
addKeyListener(this);
addMouseListener(this);
addMouseMotionListener(this);
setBorder(BorderFactory.createLineBorder(Color.black));
}
public void paintComponent(Graphics g)
{
try
{
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
Graphics2D g2 = (Graphics2D)g;
if(color!=null)
g2.setPaint(color);
if(start!=null && end!=null)
{
if(selected==("elipse"))
g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y));
else if(selected==("rect"))
g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y));
else if(selected==("rrect"))
g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11);
else if(selected==("line"))
g2.drawLine(start.x,start.y,end.x,end.y);
else if(selected==("poly"))
{
g2.drawLine(start.x,start.y,end.x,end.y);
client.broadcast(start, "start", "poly", "drag", selectedcolor);
client.broadcast(end, "end", "poly", "drag", selectedcolor);
}
}
if(tooltip==true)
{
System.out.println(selected);
if(selected=="text")
{
g2.drawString("|", tip.x, tip.y-5);
g2.drawString("Click to add text", tip.x+10, tip.y+23);
g2.drawString("__", label.x+post, label.y);
}
if(selected=="erase")
{
g2.setPaint(new Color(237,237,237));
g2.fillRect(tip.x-10,tip.y-10,10,10);
g2.setPaint(color);
g2.drawRect(tip.x-10,tip.y-10,10,10);
}
}
}
catch(Exception e)
{}
}
//Function to draw the shape on image
public void draw()
{
Graphics2D g2 = (Graphics2D) image.createGraphics();
Font font=new Font("Times New Roman",Font.PLAIN,14);
g2.setFont(font);
g2.setPaint(color);
if(start!=null && end!=null)
{
if(selected=="line")
g2.drawLine(start.x, start.y, end.x, end.y);
else if(selected=="elipse")
g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y));
else if(selected=="rect")
g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y));
else if(selected==("rrect"))
g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11);
else if(selected==("poly"))
{
g2.drawLine(start.x,start.y,end.x,end.y);
client.broadcast(start, "start", "poly", "release", selectedcolor);
client.broadcast(end, "end", "poly", "release", selectedcolor);
}
fillstart=start;
fillend=end;
fillshape=selected;
}
if(selected!="poly")
{
start=null;
end=null;
}
if(label!=null)
{
if(selected==("text"))
{
g2.drawString(key,label.x,label.y);
client.broadcast(label, key, "text", "release", selectedcolor);
}
}
repaint();
g2.dispose();
}
//Function which provides the erase functionality
public void erase()
{
Graphics2D pic=(Graphics2D) image.createGraphics();
Color erasecolor=new Color(237,237,237);
pic.setPaint(erasecolor);
if(start!=null)
pic.fillRect(start.x-10, start.y-10, 10, 10);
}
//To set the size of the image
public void setImage(BufferedImage image)
{
this.image = image;
}
//Function to add buttons into the panel, calling this function returns a panel
public JPanel shapeButtons()
{
JPanel shape=new JPanel();
shape.setBackground(new Color(181, 197, 210));
shape.setLayout(new GridLayout(5,2,2,4));
shape.setBounds(0, 2, 74, 166);
rectangle.addActionListener(this);
rectangle.setToolTipText("Rectangle");
line.addActionListener( this);
line.setToolTipText("Line");
erase.addActionListener(this);
erase.setToolTipText("Eraser");
roundrect.addActionListener(this);
roundrect.setToolTipText("Round edge Rectangle");
polygon.addActionListener(this);
polygon.setToolTipText("Polygon");
text.addActionListener(this);
text.setToolTipText("Text");
fill.addActionListener(this);
fill.setToolTipText("Fill with colour");
elipse.addActionListener(this);
elipse.setToolTipText("Elipse");
save.addActionListener(this);
shape.add(elipse);
shape.add(rectangle);
shape.add(roundrect);
shape.add(polygon);
shape.add(line);
shape.add(text);
shape.add(fill);
shape.add(erase);
shape.add(save);
return shape;
}
public JPanel colourButtons()
{
JPanel colourbox=new JPanel();
colourbox.setBackground(new Color(181, 197, 210));
colourbox.setLayout(new GridLayout(8,2,8,8));
colourbox.setBounds(0,323,70,140);
//colourbox.add(empty);
for(int i=0;i<16;i++)
{
colourbutton[i]=new JButton();
colourbox.add(colourbutton[i]);
if(i==0)
colourbutton[0].setBackground(Color.black);
else if(i==1)
colourbutton[1].setBackground(Color.white);
else if(i==2)
colourbutton[2].setBackground(Color.red);
else if(i==3)
colourbutton[3].setBackground(Color.orange);
else if(i==4)
colourbutton[4].setBackground(Color.blue);
else if(i==5)
colourbutton[5].setBackground(Color.green);
else if(i==6)
colourbutton[6].setBackground(Color.pink);
else if(i==7)
colourbutton[7].setBackground(Color.magenta);
else if(i==8)
colourbutton[8].setBackground(Color.cyan);
else if(i==9)
colourbutton[9].setBackground(Color.black);
else if(i==10)
colourbutton[10].setBackground(Color.yellow);
else if(i==11)
colourbutton[11].setBackground(new Color(131,168,43));
else if(i==12)
colourbutton[12].setBackground(new Color(132,0,210));
else if(i==13)
colourbutton[13].setBackground(new Color(193,17,92));
else if(i==14)
colourbutton[14].setBackground(new Color(129,82,50));
else if(i==15)
colourbutton[15].setBackground(new Color(64,128,128));
colourbutton[i].addActionListener(this);
}
return colourbox;
}
public void fill()
{
if(selected=="fill")
{
Graphics2D g2 = (Graphics2D) image.getGraphics();
g2.setPaint(color);
System.out.println("Fill");
if(fillshape=="elipse")
g2.fillOval(fillstart.x, fillstart.y, (fillend.x-fillstart.x),(fillend.y-fillstart.y));
else if(fillshape=="rect")
g2.fillRect(fillstart.x, fillstart.y, (fillend.x-fillstart.x),(fillend.y-fillstart.y));
else if(fillshape==("rrect"))
g2.fillRoundRect(fillstart.x, fillstart.y, (fillend.x-fillstart.x),(fillend.y-fillstart.y),11,11);
// else if(fillshape==("poly"))
// g2.drawPolygon(x,y,2);
}
repaint();
}
//To save the image drawn
public void save()
{
try
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
JFileChooser fc = new JFileChooser();
fc.showSaveDialog(this);
encoder.encode(image);
byte[] jpgData = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(fc.getSelectedFile()+".jpeg");
fos.write(jpgData);
fos.close();
//add replce confirmation here
}
catch (IOException e)
{
System.out.println(e);
}
}
public void mouseClicked(MouseEvent e)
{
}
@Override
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent e)
{
if(selected=="line"||selected=="text")
{
start=e.getPoint();
client.broadcast(start,"start", selected,"press", selectedcolor);
}
else if(selected=="elipse"||selected=="rect"||selected=="rrect")
mp = e.getPoint();
else if(selected=="poly")
{
if(first==true)
{
start=e.getPoint();
//client.broadcast(start,"start", selected,"press", selectedcolor);
}
else if(first==false)
{
end=e.getPoint();
repaint();
//client.broadcast(end,"end", selected,"press", selectedcolor);
}
}
else if(selected=="erase")
{
start=e.getPoint();
erase();
}
}
public void mouseReleased(MouseEvent e)
{
if(selected=="text")
{
System.out.println("Reset");
key="";
post=0;
label=new Point();
label=e.getPoint();
grabFocus();
}
if(start!=null && end!=null)
{
if(selected=="line")
{
end=e.getPoint();
client.broadcast(end,"end", selected,"release", selectedcolor);
draw();
}
else if(selected=="elipse"||selected=="rect"||selected=="rrect")
{
end.x = Math.max(mp.x,e.getX());
end.y = Math.max(mp.y,e.getY());
client.broadcast(end,"end", selected,"release", selectedcolor);
draw();
}
else if(selected=="poly")
{
draw();
first=false;
start=end;
end=null;
}
}
}
public void mouseDragged(MouseEvent e)
{
if(end==null)
end = new Point();
if(start==null)
start = new Point();
if(selected=="line")
{
end=e.getPoint();
client.broadcast(end,"end", selected,"drag", selectedcolor);
}
else if(selected=="erase")
{
start=e.getPoint();
erase();
client.broadcast(start,"start", selected,"drag", selectedcolor);
}
else if(selected=="elipse"||selected=="rect"||selected=="rrect")
{
start.x = Math.min(mp.x,e.getX());
start.y = Math.min(mp.y,e.getY());
end.x = Math.max(mp.x,e.getX());
end.y = Math.max(mp.y,e.getY());
client.broadcast(start,"start", selected,"drag", selectedcolor);
client.broadcast(end,"end", selected,"drag", selectedcolor);
}
else if(selected=="poly")
end=e.getPoint();
System.out.println(tooltip);
if(tooltip==true)
{
if(selected=="erase")
{
Graphics2D g2=(Graphics2D) getGraphics();
tip=e.getPoint();
g2.drawRect(tip.x-10,tip.y-10,10,10);
}
}
repaint();
}
public void mouseMoved(MouseEvent e)
{
if(selected=="text" ||selected=="erase")
{
tip=new Point();
tip=e.getPoint();
tooltip=true;
repaint();
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==elipse)
selected="elipse";
else if(e.getSource()==line)
selected="line";
else if(e.getSource()==rectangle)
selected="rect";
else if(e.getSource()==erase)
{
selected="erase";
tooltip=true;
System.out.println(selected);
erase();
}
else if(e.getSource()==roundrect)
selected="rrect";
else if(e.getSource()==polygon)
{
selected="poly";
first=true;
start=null;
}
else if(e.getSource()==text)
{
selected="text";
tooltip=true;
}
else if(e.getSource()==fill)
{
selected="fill";
fill();
}
else if(e.getSource()==save)
save();
if(e.getSource()==colourbutton[0])
{
color=Color.black;
selectedcolor="black";
}
else if(e.getSource()==colourbutton[1])
{
color=Color.white;
selectedcolor="white";
}
else if(e.getSource()==colourbutton[2])
{
color=Color.red;
selectedcolor="red";
}
else if(e.getSource()==colourbutton[3])
{
color=Color.orange;
selectedcolor="orange";
}
else if(e.getSource()==colourbutton[4])
{
selectedcolor="blue";
color=Color.blue;
}
else if(e.getSource()==colourbutton[5])
{
selectedcolor="green";
color=Color.green;
}
else if(e.getSource()==colourbutton[6])
{
selectedcolor="pink";
color=Color.pink;
}
else if(e.getSource()==colourbutton[7])
{
selectedcolor="magenta";
color=Color.magenta;
}
else if(e.getSource()==colourbutton[8])
{
selectedcolor="cyan";
color=Color.cyan;
}
}
@Override
public void keyPressed(KeyEvent e)
{
//System.out.println(e.getKeyChar()+" : "+e.getKeyCode());
if(label!=null)
{
if(e.getKeyCode()==10) //Check for Enter key
{
label.y=label.y+14;
key="";
post=0;
repaint();
}
else if(e.getKeyCode()==8) //Backspace
{
try{
Graphics2D g2 = (Graphics2D) image.getGraphics();
g2.setPaint(new Color(237,237,237));
g2.fillRect(label.x+post-7, label.y-13, 14, 17);
if(post>0)
post=post-6;
keycode=0;
key=key.substring(0, key.length()-1);
System.out.println(key.substring(0, key.length()));
repaint();
Point broadcastlabel=new Point();
broadcastlabel.x=label.x+post-7;
broadcastlabel.y=label.y-13;
client.broadcast(broadcastlabel, key, "text", "backspace", selectedcolor);
}
catch(Exception ex)
{}
}
//Block invalid keys
else if(!(e.getKeyCode()>=16 && e.getKeyCode()<=20
|| e.getKeyCode()>=112 && e.getKeyCode()<=123
|| e.getKeyCode()>=33 && e.getKeyCode()<=40
|| e.getKeyCode()>=144 && e.getKeyCode()<=145
|| e.getKeyCode()>=524 && e.getKeyCode()<=525
||e.getKeyCode()==27||e.getKeyCode()==155
||e.getKeyCode()==127))
{
key=key+e.getKeyChar();
post=post+6;
draw();
}
}
}
@Override
public void keyReleased(KeyEvent e)
{
}
@Override
public void keyTyped(KeyEvent e)
{
}
}
class Button extends JButton
{
String name;
int i;
public Button(String name)
{
this.name=name;
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public Button(int i)
{
this.i=i;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//g2.setStroke(new BasicStroke(1.2f));
if (name == "line") g.drawLine(5,5,30,30);
if (name == "elipse") g.drawOval(5,7,25,20);
if (name== "rect") g.drawRect(5,5,25,23);
if (name== "roundrect") g.drawRoundRect(5,5,25,23,10,10);
int a[]=new int[]{20,9,20,23,20};
int b[]=new int[]{9,23,25,20,9};
if (name== "poly") g.drawPolyline(a, b, 5);
if (name== "text") g.drawString("Text",8, 24);
}
}
© Stack Overflow or respective owner