BufferedImage to Image

ok im doing this...
public class Map{
  static ImageIcon image;
  public Map() {
  public void paint(Graphics g){
    Graphics2D g2d = (Graphics2D)g;
    Image im = Toolkit.getDefaultToolkit().getImage("images\\map.gif");
    g2d.drawImage(im,0,0,Config.map);
    int width = 400;
    int height = 400;
    BufferedImage bimage = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.OPAQUE);
    image = new ImageIcon(bimage);
}Config.map is a JPanel
When i do this i just get an empty ImageIcon. why is that?

Yeah ill create the image outside...
The reason i want to convert an image to a bufferedImage and then back is because i want to draw on it before i convert it back to an image. (which then gets put into the ImageIcon so that i can use it as a JLabel...
So is this the right way?
Image im = Toolkit.getDefaultToolkit().getImage("images\\map.gif");
BufferedImage thumbImage = new BufferedImage(400,400,BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = im.createGraphics();
g2d.drawImage(im,0,0,400,400,null);
BufferedImage bimage = g2d.getDeviceConfiguration().createCompatibleImage(400, 400, Transparency.OPAQUE);
ImageIcon ima = new ImageIcon(bimage);Cause if i do that i get a black image... not sure why...

Similar Messages

  • Creating BufferedImage from Image

    I've figured out one way to create a BufferedImage from an Image, but I'm sure it's not the best way.Image im = Toolkit.getDefaultToolkit().getImage(files.getAbsolutePath());
    JLabel jl = new JLabel(new ImageIcon(im));
    BufferedImage bim = new BufferedImage(im.getWidth(null), im.getHeight(null), BufferedImage.TYPE_BYTE_INDEXED);
    Graphics g = bim.getGraphics();
    jl.paint(bim.getGraphics());
    This works, but I'm sure there has to be a better/easier way. Any suggestions?
    Thanks,
    m

    close, the best way is this...
    public BufferedImage createBufferedImage(Image img)
    BufferedImage bimg = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_RGB);//or whatever type is appropriate
    bimg.getGraphics().drawImage(img,0,0,null);
    return bimg;
    }

  • BufferedImage Combining images

    I am working with the BufferedImage class. Basically I have two images
    that I want to combine together BEFORE I paint them to the screen. Can someone please show me how to do this. I have not been able to figure this out, although I think it will be easy for a seasoned Java Graphics developer.
    1 Image FirstImage = getToolkit().getImage("front.gif");
    2 Image MyButtonImage = getToolkit().getImage("buttons.gif");
    3 MediaTracker mt = new MediaTracker(this);
    4 mt.addImage(FirstImage, 1); mt.addImage(MyButtonImage, 2);
    5 bi_BackGround = new BufferedImage(FirstImage.getWidth(this),
    6 FirstImage.getHeight(this),
    7 BufferedImage.TYPE_INT_ARGB);
    8 bi_MyButtonImage = new BufferedImage(MyButtonImage.getWidth(this),
    9 MyButtonImage.getHeight(this),
    10 BufferedImage.TYPE_INT_ARGB);
    11
    12 Graphics2D dcBackGround = bi_BackGround.createGraphics();
    13 Graphics2D dcButton = bi_MyButtonImage.createGraphics();
    14
    15
    16 dcBackGround.drawImage(FirstImage, 0,0, null);
    17 dcBackGround.drawOval(10,10,5,5); // Draw an oval on the first image
    18 // I am under the assumption that lines 16, and 17
    19 dcButton.drawImage(FirstImage, 0,0, null);
    // Next draw image of a button on the first image.
    20 dcButton.drawImage(MyButtonImage, 0,0, null);
    21 // We now have a background image with a button on it.
    22 }
    23
    24 public void paintComponent(Graphics g) {
    25 super.paintComponent(g);
    26 Graphics2D g2D = (Graphics2D) g;
    27 g2D.drawImage(bi_MyButtonImage, x, y, this); // Display final image
    28}

    Actually the code could be working but I have just found out that
    only a portion of the first image is being shown. Then I think the second image is overlayed with the same dimensions of the first image, thus hiding the second image. For some reason, the hieght of the bitmap is not correct. Note that this is how I get the height.
    FirstImage.getWidth(this),
    FirstImage.getHeight(this)
    Please help

  • How to change bufferedImage to Image at Phone

    i transfer the buffered Image at a byte array format to phone, but i can't change the byte array to Image at the phone, how can i do that?

    Hi Jaime,
    Thanks is done .. 
    On dx650 phone background change is same procedure or different.
    File size is different i know but list.xml is same or different ?
    Or i can upload only one list.xml file just line add for dx650 phone.
    Thanks
    Afzal 

  • How to convert BufferedImage back to Image

    I have an Image from ImageIcon and i want to cut it using BufferedImage.getSubImage(...) and now from BufferedImage i want to turn it to Image again so that i can put in ImageIcon.
    Here is my code:
    URL img = new URL(location);
    ImageIcon imgIcon = new ImageIcon(img);
    Image image = imgIcon.getImage();
    //turn image into bufferedImage via graphic draw
    BufferedImage bi = new BufferedImage(..);
    Graphics g = bi.createGraphics();
    g.drawImage(image,0,0,null);
    bi.getSubImage(...);
    // how to turn bi back to Image newImage
    any ideas??

    More correctly, BufferedImage extends Image as Image is an abstract class and not an interface.
    Shaun

  • Converting a BufferedImage to an Image

    I have a program with some BufferedImages that the user needs to be able to drag around the screen.
    1) The dragging process is very sluggish when I use BufferedImages, but not when I use normal Images. Is this normal, or is something wrong with my program?
    2) If using Images is the only way to fix this problem, how do I draw my BufferedImages into Images or convert them to Images? They have to start out as BufferedImages so that they can undergo a one-time rescaling operation.

    Where can I find out what a profiler is and how to use one?
    Here is an abbreviated version of the code. A non-buffered Image is available for dragging here, and it too drags sluggishly unless you eliminate the line of code that draws the BufferedImages to the screen. There is probably something else wrong with this program, because at one point dragging the BufferedImages did work well. When the problem appeared I tore my code apart trying to find out what I had messed up, but after reversing all the recent changes I had not eliminated the problem and was left mystified.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.lang.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    public class Hanoi2 extends JFrame implements MouseListener, MouseMotionListener, ActionListener{
         private GraphicsDevice device;
         Landscape panel=new Landscape();
         JMenuBar bar=new JMenuBar();
         JMenu menu1=new JMenu("Game");
         JMenuItem m11=new JMenuItem("New Game");
         JMenuItem m12=new JMenuItem("Save Game");
         JMenuItem m13=new JMenuItem("Load Game");
         JMenuItem m14=new JMenuItem("Exit");
         JMenu menu2=new JMenu("Options");
         JMenu m21=new JMenu("Disk Number");
         JRadioButtonMenuItem sm11=new JRadioButtonMenuItem("4");
         JRadioButtonMenuItem sm12=new JRadioButtonMenuItem("5");
         JRadioButtonMenuItem sm13=new JRadioButtonMenuItem("6");
         JRadioButtonMenuItem sm14=new JRadioButtonMenuItem("7");
         JRadioButtonMenuItem sm15=new JRadioButtonMenuItem("8");
         JRadioButtonMenuItem sm16=new JRadioButtonMenuItem("9");
         JRadioButtonMenuItem sm17=new JRadioButtonMenuItem("10");
         JMenu m22=new JMenu("Disk Set");
         JRadioButtonMenuItem sm21=new JRadioButtonMenuItem("Stone");
         JRadioButtonMenuItem sm22=new JRadioButtonMenuItem("Glass");
         JRadioButtonMenuItem sm23=new JRadioButtonMenuItem("Pattern");
         JMenu m23=new JMenu("Backdrop");
         JRadioButtonMenuItem sm31=new JRadioButtonMenuItem("Spirals");
         JRadioButtonMenuItem sm32=new JRadioButtonMenuItem("Stars");
         JRadioButtonMenuItem sm33=new JRadioButtonMenuItem("Dots and Flowers");
         JRadioButtonMenuItem sm34=new JRadioButtonMenuItem("Psychedelic");
         JRadioButtonMenuItem sm35=new JRadioButtonMenuItem("Smart Sky");
         JMenu menu3=new JMenu("Help");
         JMenuItem m31=new JMenuItem("Instructions");
         JMenuItem m32=new JMenuItem("About");
         int numberdisks=4;
         int numberdisksthisgame=0;
         int diskset=0;
         int backdrop=0;
         boolean isgame=false;
         int[] diskstack={-1,-1,-1};
         int[][] poledisks=new int[3][10];
         Image[] backs=new Image[5];
         Image[][] disks=new Image[3][10];
         Image[] poles=new Image[3];
         Image cloth;
         Image company;
         Image title;
         MediaTracker tracker=new MediaTracker(this);
         int[][] diskspot=new int[2][10];
         BufferedImage[][] disksr=new BufferedImage[3][10];
         Graphics2D[][] disksg=new Graphics2D[3][10];
         BufferedImage[] polesr=new BufferedImage[3];
         Graphics2D[] polesg=new Graphics2D[3];
         boolean goer=false;
         public Hanoi2(GraphicsDevice device){
         super(device.getDefaultConfiguration());
         this.device=device;
         setTitle("Tower of Hanoi");
         setDefaultCloseOperation(EXIT_ON_CLOSE);
         title=Toolkit.getDefaultToolkit().getImage("Hanoi/Title.gif");
         company=Toolkit.getDefaultToolkit().getImage("Hanoi/Company.gif");
         cloth=Toolkit.getDefaultToolkit().getImage("Hanoi/clothspread2.gif");
         poles[0]=Toolkit.getDefaultToolkit().getImage("Hanoi/woodpole1.gif");
         poles[1]=Toolkit.getDefaultToolkit().getImage("Hanoi/woodpole2.gif");
         poles[2]=Toolkit.getDefaultToolkit().getImage("Hanoi/woodpole3.gif");
         backs[0]=Toolkit.getDefaultToolkit().getImage("Hanoi/background1.gif");
         backs[1]=Toolkit.getDefaultToolkit().getImage("Hanoi/background2.gif");
         backs[2]=Toolkit.getDefaultToolkit().getImage("Hanoi/background3.gif");
         backs[3]=Toolkit.getDefaultToolkit().getImage("Hanoi/background4.gif");
         backs[4]=Toolkit.getDefaultToolkit().getImage("Hanoi/background5.gif");
         disks[0][0]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone1.gif");
         disks[0][1]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone2.gif");
         disks[0][2]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone3.gif");
         disks[0][3]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone4.gif");
         disks[0][4]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone5.gif");
         disks[0][5]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone6.gif");
         disks[0][6]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone7.gif");
         disks[0][7]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone8.gif");
         disks[0][8]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone9.gif");
         disks[0][9]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone10.gif");
         disks[1][0]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass1.gif");
         disks[1][1]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass2.gif");
         disks[1][2]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass3.gif");
         disks[1][3]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass4.gif");
         disks[1][4]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass5.gif");
         disks[1][5]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass6.gif");
         disks[1][6]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass7.gif");
         disks[1][7]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass8.gif");
         disks[1][8]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass9.gif");
         disks[1][9]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass10.gif");
         disks[2][0]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve1.gif");
         disks[2][1]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve2.gif");
         disks[2][2]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve3.gif");
         disks[2][3]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve4.gif");
         disks[2][4]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve5.gif");
         disks[2][5]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve6.gif");
         disks[2][6]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve7.gif");
         disks[2][7]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve8.gif");
         disks[2][8]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve9.gif");
         disks[2][9]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve10.gif");
         for(int i=0; i<10; i++){
         tracker.addImage(disks[0], 0);
         tracker.addImage(disks[1][i], 0);
         tracker.addImage(disks[2][i], 0);}
         tracker.addImage(poles[0], 0);
         tracker.addImage(poles[2], 0);
         tracker.addImage(poles[1], 0);
         try{
         tracker.waitForID(0);
         }catch(Exception e){}
         tracker.addImage(title, 0);
         tracker.addImage(company, 0);
         tracker.addImage(backs[0], 0);
         tracker.addImage(backs[1], 0);
         tracker.addImage(backs[2], 0);
         tracker.addImage(backs[3], 0);
         tracker.addImage(backs[4], 0);
         tracker.addImage(cloth, 0);
         for(int i=0; i<3; i++){
         polesr[i]=new BufferedImage(11,350,BufferedImage.TYPE_INT_RGB);
         polesg[i]=polesr[i].createGraphics();}
         for(int v=0; v<3; v++){
         for(int i=0; i<10; i++){
         disksr[v][i]=new BufferedImage(65+i*15,35,BufferedImage.TYPE_INT_RGB);
         disksg[v][i]=disksr[v][i].createGraphics();
         int y=0;
         int z=-75;
         int q=0;
         for(int x=0; x<65+i*15+2; x+=2){
         if(65+i*15<81) q=7;
         if((65+i*15>80)&&(65+i*15<111)) q=6;
         if((65+i*15>110)&&(65+i*15<141)) q=4;
         if((65+i*15>140)&&(65+i*15<186)) q=3;
         if(65+i*15>185) q=2;
         if((x<(65+i*15)/8)||(x>(65+i*15)-((65+i*15)/8))) {q=q+3;}
         else if((x<(65+i*15)/4)||(x>(65+i*15)-((65+i*15)/4))) {q=q+2;}
         else if((x<(65+i*15)/3)||(x>(65+i*15)-((65+i*15)/3))) {q=q+1;}
         if(x<(65+i*15)/4) z+=q;
         if(x>=(65+i*15)/4) z-=q;
         BufferedImage bi=new BufferedImage(65+i*15,35,BufferedImage.TYPE_INT_RGB);
         BufferedImage bi2=new BufferedImage(65+i*15,35,BufferedImage.TYPE_INT_RGB);
         Graphics2D big;
         big=bi.createGraphics();
         big.drawImage(disks[v][i],0,0,this);
         RescaleOp rop = new RescaleOp(1.1f,(float)(z), null);
    rop.filter(bi,bi2);
         Rectangle2D.Double rect=new Rectangle2D.Double(65+i*15-x,0,4,35);
         disksg[v][i].setClip(rect);
         disksg[v][i].drawImage(bi2,0,0,this);}
         if((v==2)&&(i==9))
         goer=true;}}
         setJMenuBar(bar);
         bar.add(menu1);
         bar.add(menu2);
         bar.add(menu3);
         menu1.add(m11);
         menu1.add(m12);
         menu1.add(m13);
         menu1.add(m14);
         menu2.add(m21);
         menu2.add(m22);
         menu2.add(m23);
         m11.addActionListener(this);
         m12.addActionListener(this);
         m13.addActionListener(this);
         m14.addActionListener(this);
         ButtonGroup group1 = new ButtonGroup();
         m21.add(sm11);
         m21.add(sm12);
         m21.add(sm13);
         m21.add(sm14);
         m21.add(sm15);
         m21.add(sm16);
         m21.add(sm17);
         group1.add(sm11);
         group1.add(sm12);
         group1.add(sm13);
         group1.add(sm14);
         group1.add(sm15);
         group1.add(sm16);
         group1.add(sm17);
         sm11.addActionListener(this);
         sm12.addActionListener(this);
         sm13.addActionListener(this);
         sm14.addActionListener(this);
         sm15.addActionListener(this);
         sm16.addActionListener(this);
         sm17.addActionListener(this);
         ButtonGroup group2 = new ButtonGroup();
         m22.add(sm21);
         m22.add(sm22);
         m22.add(sm23);
         group2.add(sm21);
         group2.add(sm22);
         group2.add(sm23);
         sm21.addActionListener(this);
         sm22.addActionListener(this);
         sm23.addActionListener(this);
         ButtonGroup group3 = new ButtonGroup();
         m23.add(sm31);
         m23.add(sm32);
         m23.add(sm33);
         m23.add(sm34);
         m23.add(sm35);
         group3.add(sm31);
         group3.add(sm32);
         group3.add(sm33);
         group3.add(sm34);
         group3.add(sm35);
         sm31.addActionListener(this);
         sm32.addActionListener(this);
         sm33.addActionListener(this);
         sm34.addActionListener(this);
         sm35.addActionListener(this);
         menu3.add(m31);
         menu3.add(m32);
         m31.addActionListener(this);
         m32.addActionListener(this);}
         int placex=0;
         int placey=0;
         class Landscape extends JPanel{
         public void paintComponent(Graphics g){
         super.paintComponent(g);
         Graphics2D g2 = (Graphics2D) g;
         try{
         tracker.waitForAll();
         }catch (InterruptedException exc){}
         if((tracker.checkAll())&&(goer==true)){
         if(isgame==false){
         g.drawImage(title,68,75,this);
         g.drawImage(company,77,250,this);}
         if(isgame==true){
         g.drawImage(backs[backdrop],0,0,this);
         g.drawImage(cloth,0,462,this);
         g.drawImage(disks[0][0],placex,placey,this);
         for(int i=0; i<10; i++){
         g2.drawImage(disksr[diskset][i],diskspot[0][i],diskspot[1][i],this);}}}}}
         public static void main(String[] args){
         try {
    UIManager.setLookAndFeel(
    UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (Exception e) { }
         GraphicsEnvironment env = GraphicsEnvironment.
    getLocalGraphicsEnvironment();
    GraphicsDevice[] devices = env.getScreenDevices();
    for (int i = 0; i < 1 /* devices.length */; i++) {
    Hanoi2 box = new Hanoi2(devices[i]);
    box.initComponents(box.getContentPane());
    box.begin();}}
         private void initComponents(Container c) {
         panel.setBackground(new java.awt.Color(201%256, 27%256, 27%256));
         panel.setPreferredSize(new Dimension(696,500));
         setContentPane(panel);}
         public void setVisible(boolean isVis) {
    super.setVisible(isVis);}
         public void begin() {
         addMouseListener(this);
         addMouseMotionListener(this);
         pack();
         setVisible(true);
         setLocationRelativeTo(null);}
         public void actionPerformed(ActionEvent e) {
         if(e.getSource()==m11){
         isgame=true;
         numberdisksthisgame=numberdisks;
         for(int i=0; i<10; i++){
         diskspot[0][i]=25+(9-i)*7;
         diskspot[1][i]=462-numberdisks*35+i*35;}
         repaint();}
    if(e.getSource()==m14){
         System.exit(0);}}
         boolean[] dragdisk={false,false,false,false,false,false,false,false,false,false};
         boolean[] istop={true,false,false,false,false,false,false,false,false,false};
         int xcheck=0;
         int ycheck=0;
         boolean dragother=false;
         int currentpole=0;
         public void mousePressed(MouseEvent e){
         int y=e.getY()-60;
         if(isgame==true){
         if((e.getX()>placex)&&(e.getX()<placex+65)&&(y>placey)&&(y<placey+35)){
         dragother=true;}
         for(int i=0; i<numberdisksthisgame; i++){
         if((e.getX()>diskspot[0][i])&&(e.getX()<diskspot[0][i]+(65+i*15))&&(y>diskspot[1][i])&&
         (y<diskspot[1][i]+35)){
         dragdisk[i]=true;
         xcheck=e.getX()-diskspot[0][i];
         ycheck=y-diskspot[1][i];}}}}
         boolean down=true;
         public void mouseDragged(MouseEvent e){
         int y=e.getY()-60;
         if(dragother==true){
         placex=e.getX();
         placey=y;
         repaint();}
         for(int i=0; i<numberdisksthisgame; i++){
         if((isgame==true)&&(dragdisk[i]==true)){
         diskspot[1][i]=y-ycheck;
         diskspot[0][i]=e.getX()-xcheck;
         repaint();}}}
         int currentpole2=0;
         int[] diskloca={25,250,475};
         public void mouseReleased(MouseEvent e){
         for(int i=0; i<numberdisksthisgame; i++){
         if(dragdisk[i]==true){
         dragdisk[i]=false;}}}
         public void mouseMoved(MouseEvent e){}
         public void mouseEntered(MouseEvent e){}
         public void mouseExited(MouseEvent e){}
         public void mouseClicked(MouseEvent e){}}

  • Image to bufferedImage takes several minutes

    Hi,
    In my program I try to convert java.awt.Image to java.awt.image.BufferedImage:
    public static BufferedImage image2BufferedImage(Image img,int w,int h){
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bi.createGraphics();
    g2d.drawImage(img, 0,0,w, h, null);
    g2d.dispose();
    return bi;
    When the image is large, g2d.drawImage(...) takes several minutes. Someone can say me what's happen?

    How i can do it?
    maybe (java -Xmx125M ...)I use: java -Xmx300M
    Did it work?

  • Image to BufferedImage

    What is the easiest way to convert a Image to a bufferedImage for writing to a file?

    The short answer is to start with a BufferedImage! For instance, use ImageIO.read to read.
    The long aswer, well here's the long answer:
    import java.awt.*;
    import java.awt.image.*;
    import java.net.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    public class X {
        //preserves image's colormodel. Assumes image is loaded
        public static BufferedImage toBufferedImage(Image image) {
            if (image instanceof BufferedImage)
                return (BufferedImage) image;
            ColorModel cm = getColorModel(image);
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            return copy(createBufferedImage(cm, width, height), image);
        public static BufferedImage toBufferedImage(Image image, int type) {
            if (image instanceof BufferedImage && ((BufferedImage)image).getType() == type)
                return (BufferedImage) image;
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            return copy(new BufferedImage(width, height, type), image);
        //Returns target. Assumes source is loaded
        public static BufferedImage copy(BufferedImage target, Image source) {
            Graphics2D g = target.createGraphics();
            g.drawImage(source, 0, 0, null);
            g.dispose();
            return target;
        public static ColorModel getColorModel(Image image) {
            try {
                PixelGrabber pg = new PixelGrabber(image, 0,0,1,1, false);
                pg.grabPixels();
                return pg.getColorModel();
            } catch (InterruptedException e) {
                throw new RuntimeException("Unexpected interruption", e);
        public static BufferedImage createBufferedImage(ColorModel cm, int w, int h) {
            WritableRaster raster = cm.createCompatibleWritableRaster(w, h);
            boolean isRasterPremultiplied = cm.isAlphaPremultiplied();
            return new BufferedImage(cm, raster, isRasterPremultiplied, null);
        //you may want to use MediaTracker directly
        public static Image load(Image image) {
            ImageIcon ii = new ImageIcon(image);
            if (ii.getImageLoadStatus() != MediaTracker.COMPLETE)
                throw new IllegalArgumentException("unable to load image");
            return image;
        //demo
        public static void main(String[] args) throws MalformedURLException {
            URL url = new URL("http://developers.sun.com/im/logo_java.gif");
            Image image = Toolkit.getDefaultToolkit().createImage(url);
            load(image);
            BufferedImage bi1 = toBufferedImage(image);
            BufferedImage bi2 = toBufferedImage(image, BufferedImage.TYPE_INT_RGB);
            JPanel cp = new JPanel();
            cp.add(createLabel(image, "original"));
            cp.add(createLabel(bi1, "buffered 1"));
            cp.add(createLabel(bi2, "buffered 2"));
            JFrame f = new JFrame("X");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(cp);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        //demo
        static JLabel createLabel(Image image, String title) {
            JLabel label = new JLabel(new ImageIcon(image));
            label.setBorder(BorderFactory.createTitledBorder(title));
            return label;
    }I give two versions of toBufferedImage: one takes just an Image and creates a BufferedImage with
    the same ColorModel. That is usually what you want, if you care. The second creates a BufferedImage
    of a given type, like TYPE_BYTE_INDEXED.

  • Image Resize: InputStream - BufferedImage

    Hi,
    I'm in a position where I'm forced to use Java SE 1.3.1_19. We use Oracle 9iAS and aren't in a position to upgrade at present.
    I know in JavaSE1.5 I can use ImageIO etc to resize images on the fly because I have written a class to do this. How can I replicated this functionality in 1.3.1_19?
    My requirements are to upload via a multipart form (using Org.Apache.Commons.FileUpload) an Image to a BLOB field in an Oracle DB. If any one can suggest a way to do this with v1.3.1_19 I would very much appreciate it.

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.swing.*;
    public class ScalingTest {
        private JScrollPane getContent() {
            Image orig = loadImage();
            BufferedImage scaled = getScaledImage(orig, 0.50);
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5,5,5,5);
            gbc.weightx = 1.0;
            panel.add(new JLabel(new ImageIcon(orig)), gbc);
            panel.add(new JLabel(new ImageIcon(scaled)), gbc);
            return new JScrollPane(panel);
        private Image loadImage() {
            String path = "images/cougar.jpg";
            InputStream is = getClass().getResourceAsStream(path);
            byte[] imageData = readData(is);
            ImageIcon icon = new ImageIcon(imageData);
            Image image = icon.getImage();
            // ImageIcon does not let you know if the image was not
            // successfully loaded so you must ask it for feedback.
            int status = icon.getImageLoadStatus();
            String result = "";
            switch(status) {
                case MediaTracker.ABORTED:
                    result = "ABORTED";
                    break;
                case MediaTracker.ERRORED:
                    result = "ERRORED";
                    break;
                case MediaTracker.COMPLETE:
                    result = "COMPLETE";
                    break;
                default:
                    result = "unexpected loadingStatus: " + status;
            System.out.println("Loading status for \"" + path + "\": " + result);
            return image;
        private byte[] readData(InputStream is) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                byte[] buffer = new byte[4096];
                int len, count = 0;
                while((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                    count += len;
                is.close();
                System.out.println("image size = " + count);
            } catch(IOException e) {
                System.out.println("read error: " + e.getMessage());
            return baos.toByteArray();
        private BufferedImage getScaledImage(Image image, double scale) {
            int w = (int)(scale*image.getWidth(null));
            int h = (int)(scale*image.getHeight(null));
            int type = BufferedImage.TYPE_INT_RGB;
            BufferedImage out = new BufferedImage(w, h, type);
            Graphics2D g2 = out.createGraphics();
            AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
            g2.drawImage(image, at, null);
            g2.dispose();
            return out;
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new ScalingTest().getContent());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Can I get an Image from a BufferedImage?

    I've been researching for about an hour, but I can't seem to find my answer...
    I am loading and parsing sprite sheets with a BufferedImage, but would like the subimages returned to be Images, not BufferedImages. Any ideas?

    Why? BufferedImage extends Image.

  • How convert Image in BufferedImage?

    Hello i have a simple problem.
    I have a Image and I would want to convert it in BufferedImage format.
    Thanks

    since I had the code anyway:
         public static BufferedImage getBufferedImage(Image img) {
              // if the image is already a BufferedImage, cast and return it
              if((img instanceof BufferedImage) && background == null) {
                   return (BufferedImage)img;
              // otherwise, create a new BufferedImage and draw the original
              // image on it
              int w = img.getWidth(null);
              int h = img.getHeight(null);
              BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2d = bi.createGraphics();
              g2d.drawImage(img, 0, 0, w, h, null);
              g2d.dispose();
              return bi;
         }

  • Confusion with Image/BufferedImage

    Hello,
    I'm trying to write an applet that displays and modifies local image files (gif). I'm running into some confusion with the different image APIs and drawing methods though.
    I want to read the files, display them, and then create new images from sections of the original ones. I wrote an applet that succesfully loads and displays files as Image objects, but then I saw that BufferedImage has a method getSubImage() that I thought I could use to create the new images.
    But my problem is that even without manipulating the images, I can't get them to display as BufferedImages. Here's the code, where I try to display the series of images twice, once as Image, once as BufferedImage, but the BI come out as black squares.
    public class myapplet extends Applet
         BufferedImage[] img = new BufferedImage[NUM_PICS];
         Image[] im = new Image[NUM_PICS];
         public void init()
              Toolkit t = Toolkit.getDefaultToolkit();
              Graphics2D bg;
              MediaTracker tracker = new MediaTracker (this);
              for(int i = 0;i<NUM_PICS;i++)
                   try
                        im[i] = t.getImage(gen.getLogo());
    //the getLogo method is from a class I wrote -
    //it returns a string with a filename
                   catch(Exception e)
                        System.out.println("ERROR: "+e.getMessage());
                   img[i] = new BufferedImage(70, 70,BufferedImage.TYPE_INT_RGB);
    bg = img[i].createGraphics();
    bg.drawImage(im[i],0,0,this);
         public void paint(Graphics g)
              Graphics2D g2 = (Graphics2D)g;
              for(int i=0;i<NUM_PICS;i++)
                   g.drawImage(im[i],10,i*70,this);
                   g2.drawImage(img[i],null,80,i*70);
    Any help would be great.

    You have to use the MediaTracker before drawing the image onto the BufferedImage:
    try {
    im[i] = t.getImage(gen.getLogo());
    tracker.addImage(im[i], i);
    tracker.waitForID(i);

  • What type of BufferedImage is needed for 24 bit image data

    Hello, i am using an image processing api, i have a 24 bit image data, i want to form a BufferedImage and set its pixel values with my data such as
    BufferedImage image = new BufferedImage(w, h, what type?);
    WritableRaster raster = image.getRaster();
    int[] imgpixels = ((DataBufferInt) raster.getDataBuffer()).getData();
    for (int i = 0; i < image.getHeight() * image.getWidth(); i++)
    imgpixels[i] = ((myArray).getRed()) << 16 | ((myArray[i]).getGreen()) << 8 | ((myArray[i]).getBlue());
    Then i will save the Buf. image to file as png. So what type of BufferedImage do i need?
    Regards.

    what is the reason when i read a 24 bit png image...it shows the type as 0 (TYPE_CUSTOM) ?
    From the the Field Detail section for the TYPE_CUSTOM field in BufferedImage: the image type is not recognized.
    You could make a new BufferedImage with TYPE_INT_RGB, or TYPE_INT_ARGB if the image has or will have transparent pixels, and copy the TYPE_CUSTOM image into it. Then you can manipulate/process the new image.

  • Need help: BufferedImage and zooming

    please help me understand what i am doing wrong. i am having a hard time understanding the concept behind BufferedImage and zooming. the applet code loads an image as its background. after loading, you can draw line segments on it. but when i try to zoom in, the image in the background remains the same in terms of size, line segments are the only ones that are being zoomed, and the mouse coordinates are confusing.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.imageio.*;
    import java.io.*;
    import java.util.ArrayList;
    import java.io.IOException;
    import java.net.URL;
    import java.awt.image.*;
    public class Testing extends JApplet {
         private String url;
         private Map map;
         public void init() {
         public void start()
              url = "http://localhost/image.gif";
                  map = new Map(url);
                 getContentPane().add(map, "Center");
                 validate();
                 map.validate();
    class Map extends JPanel implements MouseListener, MouseMotionListener{
         private Image image;
         private ArrayList<Point2D> points;
         private ArrayList<Line2D> lineSegment;
         private Point2D startingPoint;
         private int mouseX;
         private int mouseY;
         private BufferedImage bimg;
         private AffineTransform xform;
         private AffineTransform inverse;
         private double zoomFactor = 1;
         public Map(String url)
                         super();
              //this.image = image;
              try
                   image = ImageIO.read(new URL(url));
              catch(Exception e)
              Insets insets = getInsets();
              xform = AffineTransform.getTranslateInstance(insets.left, insets.top);
              xform.scale(zoomFactor,zoomFactor);
              try {
                   inverse = xform.createInverse();
              } catch (NoninvertibleTransformException e) {
                   System.out.println(e);
              points = new ArrayList();
              startingPoint = new Point();
              bimg = new BufferedImage(this.image.getWidth(this), this.image.getHeight(this), BufferedImage.TYPE_INT_ARGB);
              repaintBImg();
              addMouseListener(this);
              addMouseMotionListener(this);
         public void paintComponent(Graphics g)
            Graphics2D g2d = (Graphics2D)g;
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING , RenderingHints.VALUE_RENDER_QUALITY ));
            bimg = (BufferedImage)image;
            g2d.drawRenderedImage(bimg, xform);
            if(!points.isEmpty())
                 for(int i=0; i<points.size(); i++)
                      if(i > 0)
                           drawLineSegment(g2d,points.get(i-1),points.get(i));
                      drawPoint(g2d, points.get(i));
            if(startingPoint != null)
                drawTempLine(startingPoint, g2d);
            else
                mouseX = 0;
                mouseY = 0;
         private void repaintBImg()
              bimg.flush();
              Graphics2D g2d = bimg.createGraphics();
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING , RenderingHints.VALUE_RENDER_QUALITY ));
            g2d.drawRenderedImage(bimg, xform);
            g2d.dispose();
         private void drawPoint(Graphics2D g2d, Point2D p)
            int x = (int)(p.getX() * zoomFactor);
            int y = (int)(p.getY() * zoomFactor);
            int w = (int)(13 * zoomFactor);
            int h = (int)(13 * zoomFactor);
              g2d.setColor(Color.ORANGE);
              g2d.setStroke(new BasicStroke(1.0F));
            g2d.fillOval(x - w / 2, y - h / 2, w, h);
            g2d.setColor(Color.BLACK);
            g2d.drawOval(x - w / 2, y - h / 2, w - 1, h - 1);
         private void drawLineSegment(Graphics2D g2d, Point2D p1, Point2D p2)
              double x1 = p1.getX() * zoomFactor;
                 double y1 = p1.getY() * zoomFactor;
                 double x2 = p2.getX() * zoomFactor;
                 double y2 = p2.getY() * zoomFactor;
                 g2d.setColor(Color.RED);
                 g2d.setStroke(new BasicStroke(3.0F));
                 g2d.draw(new java.awt.geom.Line2D.Double(x1, y1, x2, y2));
             private void drawTempLine(Point2D p, Graphics2D g2d)
                 int startX = (int)(p.getX() * zoomFactor);
                 int startY = (int)(p.getY() * zoomFactor);
                 if(mouseX != 0 && mouseY != 0)
                         g2d.setColor(Color.RED);
                          g2d.setStroke(new BasicStroke(2.0F));
                          g2d.drawLine(startX, startY, mouseX, mouseY);
         public void mouseClicked(MouseEvent e)
         public void mouseDragged(MouseEvent e)
              mouseX = (int)(e.getX()*zoomFactor);
              mouseY = (int)(e.getY()*zoomFactor);
              repaint();
         public void mousePressed(MouseEvent e)
              if(e.getButton() == 1)
                   points.add(inverse.transform(e.getPoint(), null));
                   if(points.size() > 0)
                        startingPoint = points.get(points.size()-1);
                        mouseX = mouseY = 0;
                   repaint();
              else if(e.getButton() == 2)
                   zoomFactor = zoomFactor + .05;
                   repaintBImg();
              else if(e.getButton() == 3)
                   zoomFactor = zoomFactor - .05;
                   repaintBImg();
         public void mouseReleased(MouseEvent e)
              if(e.getButton() == 1)
                   points.add(inverse.transform(e.getPoint(), null));
              repaint();
         public void mouseEntered(MouseEvent mouseevent)
         public void mouseExited(MouseEvent mouseevent)
         public void mouseMoved(MouseEvent mouseevent)
    }Message was edited by:
    hardc0d3r

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.awt.geom.*;
    import java.io.*;
    import java.net.URL;
    import java.util.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ZoomTesting extends JApplet {
        public void init() {
            //String dir = "file:/" + System.getProperty("user.dir");
            //System.out.printf("dir = %s%n", dir);
            String url = "http://localhost/image.gif";
                         //dir + "/images/cougar.jpg";
            MapPanel map = new MapPanel(url);
            getContentPane().add(map, "Center");
        public static void main(String[] args) {
            JApplet applet = new ZoomTesting();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(applet);
            f.setSize(400,400);
            f.setLocation(200,200);
            applet.init();
            f.setVisible(true);
    class MapPanel extends JPanel implements MouseListener, MouseMotionListener {
        private BufferedImage image;
        private ArrayList<Point2D> points;
        private Point2D startingPoint;
        private int mouseX;
        private int mouseY;
        private AffineTransform xform;
        private AffineTransform inverse;
        RenderingHints hints;
        private double zoomFactor = 1;
        public MapPanel(String url) {
            super();
            try {
                image = ImageIO.read(new URL(url));
            } catch(Exception e) {
                System.out.println(e.getClass().getName() +
                                   " = " + e.getMessage());
            Map<RenderingHints.Key, Object> map =
                        new HashMap<RenderingHints.Key, Object>();
            map.put(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            map.put(RenderingHints.KEY_RENDERING,
                    RenderingHints.VALUE_RENDER_QUALITY);
            hints = new RenderingHints(map);
            setTransforms();
            points = new ArrayList<Point2D>();
            startingPoint = new Point();
            addMouseListener(this);
            addMouseMotionListener(this);
        private void setTransforms() {
            Insets insets = getInsets();
            xform = AffineTransform.getTranslateInstance(insets.left, insets.top);
            xform.scale(zoomFactor,zoomFactor);
            try {
                inverse = xform.createInverse();
            } catch (NoninvertibleTransformException e) {
                System.out.println(e);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)g;
            g2d.setRenderingHints(hints);
            g2d.drawRenderedImage(image, xform);
            if(!points.isEmpty()) {
                for(int i=0; i<points.size(); i++) {
                    if(i > 0)
                        drawLineSegment(g2d,points.get(i-1),points.get(i));
                    drawPoint(g2d, points.get(i));
            if(startingPoint != null) {
                drawTempLine(startingPoint, g2d);
            } else {
                mouseX = 0;
                mouseY = 0;
        private void drawPoint(Graphics2D g2d, Point2D p) {
            int x = (int)(p.getX() * zoomFactor);
            int y = (int)(p.getY() * zoomFactor);
            int w = (int)(13 * zoomFactor);
            int h = (int)(13 * zoomFactor);
            g2d.setColor(Color.ORANGE);
            g2d.setStroke(new BasicStroke(1.0F));
            g2d.fillOval(x - w / 2, y - h / 2, w, h);
            g2d.setColor(Color.BLACK);
            g2d.drawOval(x - w / 2, y - h / 2, w - 1, h - 1);
        private void drawLineSegment(Graphics2D g2d, Point2D p1, Point2D p2) {
            double x1 = p1.getX() * zoomFactor;
            double y1 = p1.getY() * zoomFactor;
            double x2 = p2.getX() * zoomFactor;
            double y2 = p2.getY() * zoomFactor;
            g2d.setColor(Color.RED);
            g2d.setStroke(new BasicStroke(3.0F));
            g2d.draw(new java.awt.geom.Line2D.Double(x1, y1, x2, y2));
        private void drawTempLine(Point2D p, Graphics2D g2d) {
            int startX = (int)(p.getX() * zoomFactor);
            int startY = (int)(p.getY() * zoomFactor);
            if(mouseX != 0 && mouseY != 0) {
                g2d.setColor(Color.RED);
                g2d.setStroke(new BasicStroke(2.0F));
                g2d.drawLine(startX, startY, mouseX, mouseY);
        public void mouseClicked(MouseEvent e) {}
        public void mouseDragged(MouseEvent e) {
            mouseX = (int)(e.getX()*zoomFactor);
            mouseY = (int)(e.getY()*zoomFactor);
            repaint();
        public void mousePressed(MouseEvent e) {
            if(e.getButton() == 1) {
                points.add(inverse.transform(e.getPoint(), null));
                if(points.size() > 0) {
                    startingPoint = points.get(points.size()-1);
                    mouseX = mouseY = 0;
            } else if(e.getButton() == 2) {
                zoomFactor = zoomFactor + .05;
                setTransforms();
            } else if(e.getButton() == 3) {
                zoomFactor = zoomFactor - .05;
                setTransforms();
            repaint();
        public void mouseReleased(MouseEvent e) {
            if(e.getButton() == 1) {
                points.add(inverse.transform(e.getPoint(), null));
            repaint();
        public void mouseEntered(MouseEvent mouseevent) {}
        public void mouseExited(MouseEvent mouseevent) {}
        public void mouseMoved(MouseEvent mouseevent) {}
    }

  • How can I get  the part image from a rectangle region?

    hi,
    I'm trying to draw a rectagle region on a picture with mouse and crop it. but the rectangle is not vertical along x-axis.that is to say, there is a angle between x-axis and the base of the rectangle. I don't know , how can I do it. Can someone give me some tip or some java-code. Thank you very much in advance.

    I completely misunderstood your question. As I read it again it seems clear and straight-forward. I'm sorry. Let's see if this is closer.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    public class CropImage
        BufferedImage original;
        CropPanel cropPanel;
        CropSelector selector;
        public CropImage()
            original = getImage();
            cropPanel = new CropPanel(original);
            selector = new CropSelector(cropPanel);
            cropPanel.addMouseListener(selector);
            cropPanel.addMouseMotionListener(selector);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(getUIPanel(), "North");
            f.getContentPane().add(new JScrollPane(cropPanel));
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        private BufferedImage getImage()
            String fileName = "images/coyote.jpg";
            BufferedImage image = null;
            try
                URL url = getClass().getResource(fileName);
                image = ImageIO.read(url);
            catch(MalformedURLException mue)
                System.err.println("url: " + mue.getMessage());
            catch(IOException ioe)
                System.err.println("read: " + ioe.getMessage());
            return image;
        private JPanel getUIPanel()
            final JButton
                mask    = new JButton("mask"),
                crop    = new JButton("crop"),
                restore = new JButton("restore");
            ActionListener l = new ActionListener()
                public void actionPerformed(ActionEvent e)
                    JButton button = (JButton)e.getSource();
                    if(button == mask)
                        selector.mask();
                    if(button == crop)
                        selector.crop();
                    if(button == restore)
                        cropPanel.restore(original);
            mask.addActionListener(l);
            crop.addActionListener(l);
            restore.addActionListener(l);
            JPanel panel = new JPanel();
            panel.add(mask);
            panel.add(crop);
            panel.add(restore);
            return panel;
        public static void main(String[] args)
            new CropImage();
    class CropPanel extends JPanel
        BufferedImage image;
        Dimension size;
        GeneralPath clip;
        Point[] corners;
        Area mask;
        boolean showMask;
        Color bgColor;
        public CropPanel(BufferedImage bi)
            image = bi;
            setSize();
            clip = new GeneralPath();
            showMask = false;
            bgColor = getBackground();
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            int x = (w - size.width)/2;
            int y = (h - size.height)/2;
            g2.drawImage(image, x, y, this);
            if(showMask)
                g2.setPaint(getBackground());
                g2.fill(mask);
            else
                g2.setPaint(Color.red);
                g2.draw(clip);
        public Dimension getPreferredSize()
            return size;
        public void setClip(Point[] p)
            corners = p;
            clip.reset();
            clip.moveTo(p[0].x, p[0].y);
            clip.lineTo(p[1].x, p[1].y);
            clip.lineTo(p[2].x, p[2].y);
            clip.lineTo(p[3].x, p[3].y);
            clip.closePath();
            repaint();
        public void clearClip()
            clip.reset();
            repaint();
        public void setMask(Area area)
            mask = area;
            showMask = true;
            repaint();
        public void setImage(BufferedImage image)
            this.image = image;
            setSize();
            showMask = false;
            clip.reset();
            repaint();
            revalidate();
        public void restore(BufferedImage image)
            setBackground(bgColor);
            setImage(image);
        private void setSize()
            size = new Dimension(image.getWidth(), image.getHeight());
    class CropSelector extends MouseInputAdapter
        CropPanel cropPanel;
        Point start, end;
        public CropSelector(CropPanel cp)
            cropPanel = cp;
        public void mask()
            Dimension d = cropPanel.getSize();
            Rectangle r = new Rectangle(0, 0, d.width, d.height);
            Area mask = new Area(r);
            Area port = new Area(cropPanel.clip);
            mask.subtract(port);
            cropPanel.setMask(mask);
        public void crop()
            Point[] p = cropPanel.corners;
            int w = p[2].x - p[0].x;
            int h = p[1].y - p[3].y;
            BufferedImage cropped = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = cropped.createGraphics();
            g2.translate(-p[0].x, -p[3].y);
            cropPanel.paint(g2);
            g2.dispose();
            cropPanel.setBackground(Color.pink);
            cropPanel.setImage(cropped);
        public void mousePressed(MouseEvent e)
            if(e.getClickCount() == 2)
                cropPanel.clearClip();
            start = e.getPoint();
        public void mouseDragged(MouseEvent e)
            end = e.getPoint();
            // locate high and low points of rectangle from start
            int dy = end.y - start.y;
            int dx = end.x - start.x;
            double theta = Math.atan2(dy, dx);
            double spoke = start.distance(end)/2;
            double side = Math.sqrt(spoke*spoke + spoke*spoke);
            Point[] corners = new Point[4];           // counter-clockwise
            corners[0] = start;                       // left
            int x = (int)(start.x + side * Math.cos(theta + Math.PI/4));
            int y = (int)(start.y + side * Math.sin(theta + Math.PI/4));
            corners[1] = new Point(x, y);             // bottom
            corners[2] = end;                         // right
            x = (int)(start.x + side * Math.cos(theta - Math.PI/4));
            y = (int)(start.y + side * Math.sin(theta - Math.PI/4));
            corners[3] = new Point(x, y);             // top
            cropPanel.setClip(corners);
    }

Maybe you are looking for

  • Many iTunes account using one Credit card

    We have purchased 15 iPad for Sale staff and would like to install a set of apps (which are purchased from company iTunes account)on all these iPad but we still allow these staff manage their own photos, music, video and they can even purchase other

  • Broadband usage not showing on my account for the ...

    For the last 2-3 months my Broadband usage has not been showing on my account website. I am on unlimited broadband but would still like to know what I have used. This has happened, for short periods, several times before but usually rectifies itself

  • Agent running but host unavailable in grid control

    hi, well yet another question, am having a bad day with grid control. I have pushed an agent out to server xxx and the agent is now monitored through grid control however, the host remains unavailable. I have done agentca -d and -f, the agent is secu

  • 5800 XpressMusic will not connect to OviSuite an...

    The apps don´t recognize it.  On the phone, no USB icon shows up on the taskbar when I activate PC Suite mode.  But when I connect or disconnect the cable to the PC, I can hear the "new hardware found" sound - usually more times in a row.   It was al

  • RegEx help requested.

    Hello, All. I am new to Java and I am not much familiar with Java regExp package as well. I am looking into it though. I have a specific question related to Reg Exp creation. We are in need of parsing a string like "XXX > 6 && YYY> 10" [Meaning varia