how to create a jpg file for a desired part of the canvas

i hav to create a jpg file from the canvas which contains basic shapes which are drawn using methods like drawOval(),drawRectangle(). i need only a part of the canvas to be saved as a jpg file i.e for example from xpos 50-100 & ypos 200-250.i need all the portions of the shapes already drawn in that area as a jpg file..

can anyone help me?

[358 byte] By [kumartna] at [2007-10-2 8:20:03]
# 1

import java.awt.*;

import java.awt.event.*;

import java.awt.image.BufferedImage;

import java.io.*;

import javax.imageio.ImageIO;

public class CanvasClip extends Canvas implements ActionListener

{

Rectangle clip;

boolean showClip;

public CanvasClip()

{

clip = new Rectangle(50, 50, 150, 150);

showClip = false;

}

public void paint(Graphics g)

{

super.paint(g);

Graphics2D g2 = (Graphics2D)g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

int w = getWidth();

int h = getHeight();

int dia = Math.min(w,h)/4;

g2.setPaint(getBackground());

g2.fillRect(0,0,w,h);

g2.setPaint(Color.blue);

g2.drawRect(w/16, h/16, w*7/8, h*7/8);

g2.setPaint(Color.red);

g2.fillOval(w/8, h/12, w*3/4, h*5/6);

g2.setPaint(Color.green.darker());

g2.fillOval(w/2-dia/2, h/2-dia/2, dia, dia);

g2.setPaint(Color.orange);

g2.drawLine(w/16+1, h/16+1, w*15/16-1, h*15/16-1);

if(showClip)

{

g2.setPaint(Color.magenta);

g2.draw(clip);

}

}

public void actionPerformed(ActionEvent e)

{

Button button = (Button)e.getSource();

String ac = button.getActionCommand();

if(ac.equals("show"))

{

showClip = !showClip;

repaint();

}

if(ac.equals("save"))

save();

}

private void save()

{

int w = clip.width;

int h = clip.height;

BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

Graphics2D g2 = img.createGraphics();

g2.translate(-clip.x, -clip.y);

paint(g2);

g2.dispose();

String ext = "jpg"; // or "png"; "bmp" okay in j2se 1.5

try

{

ImageIO.write(img, "jpg", new File("canvasClip.jpg"));

}

catch(IOException ioe)

{

System.err.println("write error: " + ioe.getMessage());

}

}

private Panel getUIPanel()

{

Button show = new Button("show clip");

Button save = new Button("save");

show.setActionCommand("show");

save.setActionCommand("save");

show.addActionListener(this);

save.addActionListener(this);

Panel panel = new Panel();

panel.add(show);

panel.add(save);

return panel;

}

public static void main(String[] args)

{

CanvasClip cc = new CanvasClip();

Frame f = new Frame();

f.addWindowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent e)

{

System.exit(0);

}

});

f.add(cc);

f.add(cc.getUIPanel(), "South");

f.setSize(400,400);

f.setLocation(200,200);

f.setVisible(true);

}

}

74philipa at 2007-7-16 22:19:03 > top of Java-index,Security,Cryptography...
# 2
thnx 4 the code sent. i will b trying this
kumartna at 2007-7-16 22:19:03 > top of Java-index,Security,Cryptography...