import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
public class ImageTest extends JApplet{
Image bg ;
public void init(){
bg = getImage(getDocumentBase(),"xyz.gif");// this is the original image which has to be drawn on the applet
//the image size is say 400 x 400
}
public void start(){}
public void paint(Graphics g)
{
g.drawImage(bg,0,0,this);
g.copyArea(50,50,20,20,40,40);//this copies the area of image at 50,50 and
// width 20 and height 20 at 90,90
/* I want to save the image at 90,90 before by being overwritten by the above
* statement and save it as another image so that I can redraw it later to its
* position
*/
}
}
> You should use code formating when posting code.
>
> Using copyArea inside paint does not overwrite your
> image.
> You can still use your original image, and just draw
> this portion of it using drawImage.
Could you please give the statement to draw the portion of overwritten image using drawImage? (for the example above)
Thanks
You should use this function:
public abstract boolean drawImage(Image img,
int dx1,
int dy1,
int dx2,
int dy2,
int sx1,
int sy1,
int sx2,
int sy2,
ImageObserver observer)
Look in the API how to use it:
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Graphics.html
// <applet code="ImageTestRx" width="400" height="400"></applet>
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageTestRx extends JApplet {
BufferedImage bg ;
BufferedImage patch;
Rectangle clip = new Rectangle(50, 50, 20, 20);
int dx = 90;
int dy = 90;
boolean firstTime = true;
public void init() {
if(bg == null)
initImages();
}
private void initImages() {
try {
bg = ImageIO.read(new File("images/cougar.jpg"));
} catch(IOException e) {
System.out.println("read error: " + e.getMessage());
}
patch = new BufferedImage(clip.width, clip.height, bg.getType());
Graphics2D g2 = patch.createGraphics();
double x = clip.x + dx;
double y = clip.y + dy;
AffineTransform at = AffineTransform.getTranslateInstance(-x, -y);
g2.drawRenderedImage(bg, at);
g2.dispose();
}
public void start() {
Thread thread = new Thread(runner);
thread.setPriority(Thread.NORM_PRIORITY);
thread.start();
}
public void stop() {
firstTime = true;
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g.drawImage(bg,0,0,this);
if(firstTime)
g.copyArea(clip.x, clip.y, clip.width, clip.height, dx, dy);
else {
double x = clip.x + dx;
double y = clip.y + dy;
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
g2.drawRenderedImage(patch, at);
}
g2.setPaint(Color.red);
g2.draw(clip);
g2.fillOval(clip.x+dx-2, clip.y+dy-2, 4, 4);
g2.drawImage(patch, 225, 325, this);
}
private Runnable runner = new Runnable() {
public void run() {
try {
Thread.sleep(3000);
} catch(InterruptedException e) {
System.out.println("interrupted");
}
firstTime = false;
repaint();
}
};
}