Convertint raw byte[] to buffered image

Hello there,
I need help. I am trying to convert raw byte[] into BufferedImage, but I recive a null pointer exception. Someone?
ImageIcon image = new ImageIcon(filename);
          int height = image.getIconHeight();
          int width = image.getIconWidth();
          BufferedImage bf = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
          bf = ImageIO.read(new File(filename));
          WritableRaster wr = bf.getWritableTile(0, 0);
          byte[] b = (byte[])(wr.getDataElements(0, 0, bf.getWidth(), bf.getHeight(), null));
          bf.releaseWritableTile(0, 0);
          System.out.println(b.length);
          JFrame fame = new JFrame("Test");
          JFrame.setDefaultLookAndFeelDecorated(true);
          fame.getContentPane().add(new JLabel(new ImageIcon(bf)));
          fame.setSize(600, 600);
          fame.show();
          BufferedImage img = new BufferedImage(image.getIconWidth(), image.getIconHeight(), BufferedImage.TYPE_INT_RGB);
          img = ImageIO.read(new ByteArrayInputStream(b));
System.out.print(img.toString());
------------------------- NULL POINTER EXCEPTION HERE----------------------
Appreciate your help

Hi,
Did you find a answer for this problem? I have the same problem!!
Could you reply me if you have a solution?
My e-mail is [email protected]
Thanks.

Similar Messages

  • Problem in sending buffered image to remote machine

    iam able to capture ithe desktop screen as a buffered image by using buffered image class in java.awt.image.but iam bot able to send that buffered image to remote machine.it is only possible to send some part of that buffered image.but iam not able to transmit the whole buffere image of my desktop.can u help.

    Hi,
    For this topic you should have a look ( 2004-07-08 The Java Specialists' Newsletter [Issue 091] )
    from Dr. Heinz Kabutz. Indeed, the newsletter is quite useful and sometimes also amazing.
    I really enjoy reading it.
    In this newsletter he is exactly doing what you wanted to know.
    He uses an ObjectOutputStream, but compresses the screenshot beforehand as follows:
        import com.sun.image.codec.jpeg.*;
        Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
        Rectangle shotArea = new Rectangle(
            defaultToolkit.getScreenSize());
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bout);
        encoder.encode(robot.createScreenCapture(shotArea));
        return bout.toByteArray();Hope that helps

  • How do I fix extremely slow rendering with buffered images?

    I've found random examples of people with this problem, but I can't seem to find any solutions in my googling. So I figured I'd go to the source. Basically, I am working on a simple platform game in java (an applet) as a surprise present for my girlfriend. The mechanics work fine, and are actually really fast, but the graphics are AWFUL. I wanted to capture some oldschool flavor, so I want to render several backgrounds scrolling in paralax (the closest background scrolls faster than far backgrounds). All I did was take a buffered image and create a graphics context for it. I pass that graphics context through several functions, drawing the background, the distant paralax, the player/entities, particles, and finally close paralax.
    Only problem is it runs at like 5 fps (estimated, I havn't actually counted).
    I KNOW this is a graphics thing, because I can make it run quite smoothly by commenting out the code to draw the background/paralax backgrounds... and that code is nothing more complicated than a graphics2d.drawImage
    So obviously I am doing something wrong here... how do I speed this up?
    Code for main class follows:
    import javax.swing.JApplet;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.event.*;
    import Entities.*;
    import Worlds.*;
    // run this applet in 640x480
    public class Orkz extends JApplet implements Runnable, KeyListener
         double x_pos = 10;
         double y_pos = 400;
         int xRes=640;
         int yRes=480;
         boolean up_held;
         boolean down_held;
         boolean left_held;
         boolean right_held;
         boolean jump_held;
         Player player;
         World world;
         BufferedImage buffer;
         Graphics2D bufferG2D;
         int radius = 20;
         public void init()
              //xRes=(int) this.getSize().getWidth();
              //yRes=(int) this.getSize().getHeight();
            buffer=new BufferedImage(xRes, yRes, BufferedImage.TYPE_INT_RGB);
            bufferG2D=buffer.createGraphics();
              addKeyListener(this);
         public void start ()
                player=new Player(320, 240, xRes,yRes);
                world=new WorldOne(player, getCodeBase(), xRes, yRes);
                player.setWorld(world);
               // define a new thread
               Thread th = new Thread (this);
               // start this thread
               th.start ();
         public void keyPressed(KeyEvent e)
              //works fine
         }//end public void keypressed
         public void keyReleased(KeyEvent e)
              //this works fine
         public void keyTyped(KeyEvent e)
         public void paint( Graphics g )
               update( g );
        public void update(Graphics g)
             Graphics2D g2 = (Graphics2D)g;              
             world.render(bufferG2D);                
             g2.drawImage(buffer, null, null);
         public void run()
              // lower ThreadPriority
              Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
              long tm;
              long tm2;
              long tm3;
              long tmAhead=0;
              // run a long while (true) this means in our case "always"
              while (true)
                   tm = System.currentTimeMillis();
                   player.moveEntity();
                  x_pos=player.getXPos();
                  y_pos=player.getYPos();
                  tm2 = System.currentTimeMillis();
                    if ((tm2-tm)<20)
                     // repaint the applet
                     repaint();
                    else
                         System.out.println("Skipped draw");
                    tm3= System.currentTimeMillis();
                    tmAhead=25-(tm3-tm);
                    try
                        if (tmAhead>0) 
                         // Stop thread for 20 milliseconds
                          Thread.sleep (tmAhead);
                          tmAhead=0;
                        else
                             System.out.println("Behind");
                    catch (InterruptedException ex)
                          System.out.println("Exception");
                    // set ThreadPriority to maximum value
                    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
         public void stop() { }
         public void destroy() { }
    }Here's the code for the first level
    package Worlds;
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.util.*;
    import javax.swing.*;
    import javax.imageio.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.io.File;
    import java.net.URL;
    import java.awt.geom.AffineTransform;
    import Entities.Player;
    public class WorldOne implements World
         Player player;
         //Location of Applet
         URL codeBase;
         // Image Resources
         BufferedImage paralax1Image;
         BufferedImage paralax2Image;
         BufferedImage backgroundImage;
         // Graphics Elements     
         int xRes;
         int yRes;
         double paralaxScale1,paralaxScale2;
         double worldSize;
         int frameX=1;
         int frameY=1;
         public WorldOne(Player player, URL codeBase, int xRes, int yRes)
              this.player=player;
              this.codeBase=codeBase;
              this.xRes=xRes;
              this.yRes=yRes;
              worldSize=4000;
            String backgroundImagePath="worlds\\world1Graphics\\WorldOneBack.png";
            String paralax1ImagePath="worlds\\world1Graphics\\WorldOnePara1.png";
            String paralax2ImagePath="worlds\\world1Graphics\\WorldOnePara2.png";
            try
            URL url1 = new URL(codeBase, backgroundImagePath);
             URL url2 = new URL(codeBase, paralax1ImagePath);
             URL url3 = new URL(codeBase, paralax2ImagePath);
            backgroundImage = ImageIO.read(url1);
            paralax1Image  = ImageIO.read(url2);
            paralax2Image = ImageIO.read(url3);
            paralaxScale1=(paralax1Image.getWidth()-xRes)/worldSize;
            paralaxScale2=(paralax2Image.getWidth()-xRes)/worldSize;
            catch (Exception e)
                 System.out.println("Failed to load Background Images in Scene");
                 System.out.println("Background Image Path:"+backgroundImagePath);
                 System.out.println("Background Image Path:"+paralax1ImagePath);
                 System.out.println("Background Image Path:"+paralax2ImagePath);
         }//end constructor
         public double getWorldSize()
              double xPos=player.getXPos();
              return worldSize;
         public void setFramePos(int frameX, int frameY)
              this.frameX=frameX;
              this.frameY=frameY;
         public int getFrameXPos()
              return frameX;
         public int getFrameYPos()
              return frameY;
         public void paralax1Render(Graphics2D renderSpace)
              int scaledFrame=(int)(paralaxScale1*frameX);
              renderSpace.drawImage(paralax1Image,-scaledFrame,0,null); //Comment this to increase performance Massively
         public void paralax2Render(Graphics2D renderSpace)
              int scaledFrame=(int)(paralaxScale2*frameX);
              renderSpace.drawImage(paralax2Image,-scaledFrame,0,null); //Comment this to increase performance Massively
         public void backgroundRender(Graphics2D renderSpace)
              renderSpace.drawImage(backgroundImage,null,null); //Comment this to increase performance Massively
         public void entityRender(Graphics2D renderSpace)
              //System.out.println(frameX);
              double xPos=player.getXPos()-frameX+xRes/2;
             double yPos=player.getYPos();
             int radius=15;
             renderSpace.setColor (Color.blue);
            // paint a filled colored circle
             renderSpace.fillOval ((int)xPos - radius, (int)yPos - radius, 2 * radius, 2 * radius);
              renderSpace.setColor(Color.blue);
         public void particleRender(Graphics2D renderSpace)
              //NYI
         public void render(Graphics2D renderSpace)
              backgroundRender(renderSpace);
              paralax2Render(renderSpace);
              entityRender(renderSpace);
              paralax1Render(renderSpace);
    }//end class WorldOneI can post more of the code if people need clarification. And to emphasize, if I take off the calls to display the background images (the 3 lines where you do this are noted), it works just fine, so this is purely a graphical slowdown, not anything else.
    Edited by: CthulhuChild on Oct 27, 2008 10:04 PM

    are the parallax images translucent by any chance? The most efficient way to draw images with transparent areas is to do something like this:
         public static BufferedImage optimizeImage(BufferedImage img)
              GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();                    
              GraphicsConfiguration gc = gd.getDefaultConfiguration();
              boolean istransparent = img.getColorModel().hasAlpha();
              BufferedImage img2 = gc.createCompatibleImage(img.getWidth(), img.getHeight(), istransparent ? Transparency.BITMASK : Transparency.OPAQUE);
              Graphics2D g = img2.createGraphics();
              g.drawImage(img, 0, 0, null);
              g.dispose();
              return img2;
         }I copied this from a util class I have and I had to modify it a little, I hope I didn't break anything.
    This piece of code does a number of things:
    - it allows the images to be hardware accelerated
    - the returned image is 100% compatible with the display, regardless of what the input image is
    - BITMASK transparent images are an incredible amount faster than translucent images
    BITMASK means that a pixel is either fully transparent or it is fully opaque; there is no alpha blending being performed. Alpha blending in software rendering mode is very slow, so this may be the bottleneck that is bothering you.
    If you require your parallax images to be translucent then I wouldn't know how to get it to draw quicker in an applet, other than trying out java 6 update 10 to see if it fixes things.

  • File chooser to buffered image

    Hi all,
    Sorry about the total newbie question; I'm trying to figure out how to convert a jpg into a buffered image, while using the file chooser to select it. I'd like to do all this in a scrollpane. Does anyone have some sample code for this, at least so I can play around? I have ideas, but I'm getting tons of errors while trying things like:
    public class ImProc extends JComponent{
    private BufferedImage source, destination;
    private JComboBox options;
    public ImProc( BufferedImage image){
    source = destination = image;
    setBackground(Color.white);
    setLayout( new BorderLayout());
    JPanel controls = new JPanel();
    options = new JComboBox(
    new String[] {"[source]", "brighten", "darken", "rotate", "scale" }
    options.addItemListener(new ItemListener(){
    public void itemStateChanged( ItemEvent ie){
    String option = (String)options.getSelectedItem();
    BufferedImageOp op = null;
    if(option.equals("[source]"))
    destination = source;
    else if(option.equals("brighten"))
    op = new RescaleOp(1.5f, 0, null);
    else if(option.equals("darken"))
    op = new RescaleOp(0.5f, 0, null);
    else if (option.equals("rotate"))
    op = new AffineTransformOp(
    AffineTransform.getRotateInstance(Math.PI / 6), null);
    else if (option.equals("scale"))
    op = new AffineTransformOp(
    AffineTransform.getScaleInstance(.5, .5), null);
    if(op != null) destination = op.filter(source, null);
    repaint();
    controls.add(options);
    add(controls, BorderLayout.SOUTH);
    public void paintComponent(Graphics g){
    int imageWidth = destination.getWidth();
    int imageHeight = destination.getHeight();
    int width = getSize().width;
    int height = getSize().height;
    g.drawImage(destination,
    (width - imageWidth) / 2, (height - imageHeight) / 2, null);
    public static void main(String[] args){
    JFileChooser chooser = new JFileChooser();
    String filename = chooser.getName();
    ImageIcon icon = new ImageIcon(filename);
    Image i = icon.getImage();
    int w = i.getWidth(null), h = i.getHeight(null);
    BufferedImage buffImage = new BufferedImage(w, h,
    BufferedImage.TYPE_INT_RGB);
    Graphics2D imageGraphics = buffImage.createGraphics();
    imageGraphics.drawImage(i, 0, 0, null);
    JFrame frame = new JFrame("Image");
    frame.getContentPane().add(new ImProc(buffImage));
    frame.setSize(buffImage.getWidth(), buffImage.getHeight());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    So, I'm stuck. Any help from anyone is appreciated.
    Thanks,
    Joe

    Now, with:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    import java.io.*;
    import javax.imageio.*;
    public class ImProc extends JComponent{
    private BufferedImage source, destination;
    private JComboBox options;
    public ImProc( BufferedImage image){
    source = destination = image;
    setBackground(Color.white);
    setLayout( new BorderLayout());
    JPanel controls = new JPanel();
    options = new JComboBox(
    new String[] {"[source]", "brighten", "darken", "rotate", "scale" }
    options.addItemListener(new ItemListener(){
    public void itemStateChanged( ItemEvent ie){
    String option = (String)options.getSelectedItem();
    BufferedImageOp op = null;
    if(option.equals("[source]"))
    destination = source;
    else if(option.equals("brighten"))
    op = new RescaleOp(1.5f, 0, null);
    else if(option.equals("darken"))
    op = new RescaleOp(0.5f, 0, null);
    else if (option.equals("rotate"))
    op = new AffineTransformOp(
    AffineTransform.getRotateInstance(Math.PI / 6), null);
    else if (option.equals("scale"))
    op = new AffineTransformOp(
    AffineTransform.getScaleInstance(.5, .5), null);
    if(op != null) destination = op.filter(source, null);
    repaint();
    controls.add(options);
    add(controls, BorderLayout.SOUTH);
    public void paintComponent(Graphics g){
    int imageWidth = destination.getWidth();
    int imageHeight = destination.getHeight();
    int width = getSize().width;
    int height = getSize().height;
    g.drawImage(destination,
    (width - imageWidth) / 2, (height - imageHeight) / 2, null);
    public static void main(String[] args){
    JFrame frame = new JFrame("Image");
    frame.setSize(300, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    JFileChooser chooser = new JFileChooser();
    //String filename = chooser.getName();
    File f = chooser.getSelectedFile();
    //String filename = f.getName();
    //ImageIcon icon = new ImageIcon(filename);
    //Image i = ImageIO.read(f);
    //int w = i.getWidth(null), h = i.getHeight(null);
    //BufferedImage buffImage = null;
    try{
    BufferedImage buffImage = ImageIO.read(f);
    catch (IOException e){
    System.out.println("Error: " + e.getMessage());
    frame.getContentPane().add(new ImProc(buffImage));
    Graphics2D imageGraphics = buffImage.createGraphics();
    imageGraphics.drawImage(buffImage, 0, 0, null);
    With this, it doesn't seem to find my variable buffImage. However, it complains if I don't use the try{} catch{}. Am I not declaring something properly?

  • How to add byte[] array based Image to the SQL Server without using parameter

    how to add byte[] array based Image to the SQL Server without using parameter.I have a column in table with the type image in sql and i want to add image array to the sql image column like below:
    I want to add image (RESIM) to the procedur like shown above but sql accepts byte[] RESIMI like System.Drowing. I whant that  sql accepts byte [] array like sql  image type
    not using cmd.ParametersAdd() method
    here is Isle() method content

    SQL Server binary constants use a hexadecimal format:
    https://msdn.microsoft.com/en-us/library/ms179899.aspx
    You'll have to build that string from a byte array yourself:
    byte[] bytes = ...
    StringBuilder builder = new StringBuilder("0x", 2 + bytes.Length * 2);
    foreach (var b in bytes)
    builder.Append(b.ToString("X2"));
    string binhex = builder.ToString();
    That said, what you're trying to do - not using parameters - is the wrong thing to do. Not only it is insecure due to the risk of SQL injection but in the case of binary data is also inefficient since these hex strings are larger than the original byte[]
    data.

  • Adding Text to a Buffered Image

    Hey
    I am trying to add text to a bufferedimage image and have tried a couple of ways.
    I cannot seem to get it to work propely though. Everytime i try, the text appears but the image appears inside the lettering of the text and not under it like i want it to.
    Could someone please explain the best way of place text on TOP of an image as i am really stuck now :(
    Thanks in advanced for any help

    Basically paint your buffered image into a new BufferedImage and then paint in the new text on top.
    Here's a demo.
    import java.awt.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class BufferedImageTest
        public static void main(String[] args)
            ImageGenerator ig = new ImageGenerator();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(ig.getOriginalImagePanel(), "North");
            f.getContentPane().add(ig.getTextPanel(), "South");
            f.setSize(400,640);
            f.setLocation(200,50);
            f.setVisible(true);
            f.getContentPane().add(ig.getNewImagePanel());
            f.validate();
            f.repaint();
    class ImageGenerator
        JPanel originalPanel = new JPanel()
            public 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();
                g2.setPaint(Color.blue);
                g2.fill(new Rectangle2D.Double(w/16, h/16, w*7/8, h*7/8));
                g2.setPaint(Color.yellow);
                g2.fill(new Rectangle2D.Double(w/8, h/8, w*3/4, h*3/4));
                g2.setPaint(Color.red);
                g2.fill(new Ellipse2D.Double(w/6, h/6, w*2/3, h*2/3));
                g2.setPaint(Color.green);
                g2.draw(new Line2D.Double(w/16, h/16, w*15/16, h*15/16));
        JPanel textPanel = new JPanel()
            Font font = new Font("lucida sans regular", Font.PLAIN, 32);
            String text = "A New Label";
            public void paintComponent(Graphics g)
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D)g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                    RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setFont(font);
                FontRenderContext frc = g2.getFontRenderContext();
                LineMetrics lm = font.getLineMetrics(text, frc);
                float textWidth = (float)font.getStringBounds(text, frc).getWidth();
                int w = getWidth();
                int h = getHeight();
                float x = (w - textWidth)/2;
                float y = (h + lm.getHeight())/2 - lm.getDescent();
                g2.drawString(text, x, y);
        public ImageGenerator()
            originalPanel.setBackground(Color.white);
            originalPanel.setPreferredSize(new Dimension(300,200));
            textPanel.setOpaque(false);
            textPanel.setPreferredSize(new Dimension(300,200));
        private BufferedImage createNewImage()
            BufferedImage image = new BufferedImage(originalPanel.getWidth(),
                                                    originalPanel.getHeight(),
                                                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            originalPanel.paint(g2);
            textPanel.paint(g2);
            g2.dispose();
            return image;
        public JPanel getOriginalImagePanel()
            return originalPanel;
        public JPanel getTextPanel()
            return textPanel;
        public JPanel getNewImagePanel()
            JPanel panel = new JPanel()
                BufferedImage image = createNewImage();
                public void paintComponent(Graphics g)
                    super.paintComponent(g);
                    Graphics2D g2 = (Graphics2D)g;
                    g2.drawImage(image, null, 0, 0);
            return panel;
    }

  • Java Grahpics2d, Buffered Image, really bad fps when rotating a image10Dpts

    Hey, i'm making a spaceship game, and i use buffered .gif that are loaded before they are used.
    (The images are only loaded once before anyone says that :D )
    However, when i have a reasonably sized image rotating in real time, such as a 533 by 182, at normal scale my fps drops really low, like into the mid teens, and i'm not sure why.
    This only seems to happen when the iamge rotates, the fps stays fine when the image is translating.
    I use Affine Transforms to do my rotating.
    And i'm already using the createCompatibleImage GraphicsConfiguration to help increase performance, but i still get this problem.
    I've also noticed if i zoom in realy close (using scaling ffrom affine transform) the same thing happens if i rotate, and my fps drops really low as well.
    and the problem with the fps dropping when rotating is alot reduced if i zoom out alot as well.
    Anyone got any idea how i can imrpove performance.
    I'm buffering images as so:
         public BufferedImage createCompatible(int width, int height, int transparency) {
              GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration() ;
              BufferedImage compatible = gc.createCompatibleImage(width,height,transparency);
              return compatible;
         }and the following code block is the one i use to render the spaceships (Actors)
         public void paint(Graphics2D g){
                   AffineTransform at = new AffineTransform();
              at.scale(Sector42Main.UNIVSCALE, Sector42Main.UNIVSCALE);
              at.translate(x
                        -(((Actor)Sector42Main.playeractors.get(FOCUS_ID)).x)
                        +((Stage.WIDTH/2)/Sector42Main.UNIVSCALE)
                        - (((Actor)Sector42Main.playeractors.get(FOCUS_ID)).getWidth()/2) ,
                        y
                        -(((Actor)Sector42Main.playeractors.get(FOCUS_ID)).y)
                        + ((Stage.HEIGHT/2)/Sector42Main.UNIVSCALE)
                        - (((Actor)Sector42Main.playeractors.get(FOCUS_ID)).getHeight()/2));
              at.rotate(r,getWidth()/2,getHeight()/2);
         at.scale(xscale, yscale);
              g.drawImage( spriteCache.getSprite(spriteNames[currentFrame]),at, stage);
         }any help would be really welcome.
    thanks.
    Message was edited by:
    MatthewH

    I've found that a lot of game development seems to involve working out exactly what you can get away with in terms of display rather than conforming to a strict model. Sure, this is changing these days, but in terms of a bitmapped sprite just how much difference will each incremement make when projected onto pixels?
    I tend to find a little experimentation with these things goes a long way - you might find that rounding your model's angle to a display angle with a much lower resolution (say, every 2 or 5 or 10 degrees) doesn't acutally make any real difference to the game (apart from letting you render frames moire quickly) once a number of sprites are flying about the place.
    Still, just one suggestion. Let us all know if you find a another way around it.
    Cheers,
    John

  • HI Please Help me with Zoom of a buffered image

    Hi All,
    Please help,
    I want to zoom the buffered image using Affine Transforms, the code shown below can rotate the buffered image now how to zoom the same buffered image using Affine Transforms.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class RotationBounds extends JPanel implements ActionListener
        BufferedImage image;
        AffineTransform at = new AffineTransform();
        Rectangle2D.Double bounds = new Rectangle2D.Double();
        double theta = 0;
        double thetaInc = Math.PI / 2;
        public void actionPerformed(ActionEvent e)
            theta += thetaInc;
            setTransform();
            repaint();
        private void setTransform()
            int iw = image.getWidth();
            int ih = image.getHeight();
            double cos = Math.abs(Math.cos(theta));
            double sin = Math.abs(Math.sin(theta));
            double width = iw * cos + ih * sin;
            double height = ih * cos + iw * sin;
            double x = (getWidth() - iw) / 2;
            double y = (getHeight() - ih) / 2;
            at.setToTranslation(x, y);
            at.rotate(theta, iw / 2.0, ih / 2.0);
            x = (getWidth() - width) / 2;
            y = (getHeight() - height) / 2;
            // Set bounding rectangle that will frame the image rotated
            // with this transform. Use this width and height to make a
            // new BuffferedImage that will hold this rotated image.
            // AffineTransformOp doesn't have this size information in
            // the translation/rotation transform it receives.
            bounds.setFrame(x - 1, y - 1, width + 1, height + 1);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            setBackground(Color.gray);
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
            if (image == null)
                initImage();
            g2.drawRenderedImage(image, at);
            // g2.setPaint(Color.blue);
            g2.draw(bounds);
            g2.setPaint(Color.green.darker());
            g2.fill(new Ellipse2D.Double(getWidth() / 2 - 2,
                getHeight() / 2 - 2, 4, 4));
        private void initImage()
            int w = 360, h = 300;
            image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(new Color(220, 240, 240));
            g2.fillRect(0, 0, w, h);
            g2.setPaint(Color.red);
            g2.drawString("Text for test", 50, 50);
            g2.drawRect(0, 0, w - 1, h - 1);
            g2.dispose();
            g2.setTransform(at);
    //        setTransform();
        private JPanel getLast()
            JButton rotateButton = new JButton("Rotate");
            rotateButton.addActionListener(this);
             JButton zoomButton = new JButton("Zoom");
            JPanel panel = new JPanel();
            panel.add(rotateButton);
            panel.add(zoomButton);
            return panel;
        public static void main(String[] args)
            RotationBounds test = new RotationBounds();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test);
            f.getContentPane().add(test.getLast(), "North");
            f.setSize(400, 400);
            f.setLocation(0, 0);
            f.setVisible(true);
    }Message was edited by:
    New_to_Java

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.util.Hashtable;
    import javax.swing.*;
    import javax.swing.event.*;
    public class RotationZoom extends JPanel {
        AffineTransform at = new AffineTransform();
        Point2D.Double imageLoc = new Point2D.Double(100.0, 50.0);
        Rectangle2D.Double bounds = new Rectangle2D.Double();
        BufferedImage image;
        double theta = 0;
        double scale = 1.0;
        final int PAD = 20;
        public RotationZoom() {
            initImage();
        public void addNotify() {
            super.addNotify();
            setTransform();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            g2.drawRenderedImage(image, at);
            g2.setPaint(Color.red);
            g2.draw(bounds);
        public Dimension getPreferredSize() {
            return new Dimension((int)(imageLoc.x + Math.ceil(bounds.width))  + PAD,
                                 (int)(imageLoc.y + Math.ceil(bounds.height)) + PAD);
        private void update() {
            setTransform();
            revalidate();
            repaint();
        private void setTransform() {
            int iw = image.getWidth();
            int ih = image.getHeight();
            double cos = Math.abs(Math.cos(theta));
            double sin = Math.abs(Math.sin(theta));
            double width  = iw*cos + ih*sin;
            double height = ih*cos + iw*sin;
            at.setToTranslation(imageLoc.x, imageLoc.y);
            at.rotate(theta, scale*iw/2.0, scale*ih/2.0);
            at.scale(scale, scale);
            double x = imageLoc.x - scale*(width - iw)/2.0;
            double y = imageLoc.y - scale*(height - ih)/2.0;
            bounds.setFrame(x, y, scale*width, scale*height);
        private void initImage() {
            int w = 240, h = 180;
            int type = BufferedImage.TYPE_INT_RGB;
            image = new BufferedImage(w,h,type);
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setBackground(new Color(220,220,240));
            g2.clearRect(0,0,w,h);
            g2.setPaint(Color.red);
            g2.draw(new CubicCurve2D.Double(0, h, w*4/3.0, h/4.0,
                                            -w/3.0, h/4.0, w, h));
            g2.setPaint(Color.green.darker());
            g2.draw(new Rectangle2D.Double(w/3.0, h/3.0, w/3.0, h/3.0));
            g2.dispose();
        private JPanel getControls() {
            JSlider rotateSlider = new JSlider(-180, 180, 0);
            rotateSlider.setMajorTickSpacing(30);
            rotateSlider.setMinorTickSpacing(10);
            rotateSlider.setPaintTicks(true);
            rotateSlider.setPaintLabels(true);
            rotateSlider.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    int value = ((JSlider)e.getSource()).getValue();
                    theta = Math.toRadians(value);
                    update();
            rotateSlider.setBorder(BorderFactory.createTitledBorder("theta"));
            int min = 50, max = 200, inc = 25;
            JSlider zoomSlider = new JSlider(min, max, 100);
            zoomSlider.setMajorTickSpacing(inc);
            zoomSlider.setMinorTickSpacing(5);
            zoomSlider.setPaintTicks(true);
            zoomSlider.setLabelTable(getLabelTable(min, max, inc));
            zoomSlider.setPaintLabels(true);
            zoomSlider.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    int value = ((JSlider)e.getSource()).getValue();
                    scale = value/100.0;
                    update();
            zoomSlider.setBorder(BorderFactory.createTitledBorder("scale"));
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            panel.add(rotateSlider, gbc);
            panel.add(zoomSlider, gbc);
            return panel;
        private Hashtable getLabelTable(int min, int max, int inc) {
            Hashtable<Integer,JComponent> table = new Hashtable<Integer,JComponent>();
            for(int j = min; j <= max; j += inc) {
                JLabel label = new JLabel(String.format("%.2f", j/100.0));
                table.put(new Integer(j), label);
            return table;
        public static void main(String[] args) {
            RotationZoom test = new RotationZoom();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(test));
            f.getContentPane().add(test.getControls(), "Last");
            f.setSize(500,500);
            f.setLocation(200,100);
            f.setVisible(true);
    }

  • Couln't  save a buffered image as BMP with java 1.4

    Dear friends,
    I tried to save a buffered image as BMP with java 1.4. When I run the program ,it executes sucessfully, but no image wasn't created. When I tried the same code with java 1.5 got the right result.
    This is the code I have written.
    public static void saveBMPFile(BufferedImage bufferredImage, String fileName) throws Exception{
              // TODO Auto-generated method stub
              try {
                   Iterator iter =
                        ImageIO.getImageWritersByMIMEType("image/bmp");
              // Get first writer
                   if (iter.hasNext()) {
                        ImageWriter writer = (ImageWriter) iter.next();
                        ImageWriteParam iwp = writer.getDefaultWriteParam();
                        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                        iwp.setCompressionType("BI_RGB");                    
                        FileImageOutputStream fios = new FileImageOutputStream(new File(fileName));
                        writer.setOutput(fios);
                        IIOImage image = new IIOImage(bufferredImage, null, null);
                        writer.write(null, image, iwp);
                        bufferredImage.flush();
                        fios.flush();
                        fios.close();
         } catch (Exception e) {                 
         throw e;
    please help me to find its solution.
    thanks & regards
    K P Jyothish

    Please use code tags http://forum.java.sun.com/help.jspa?sec=formatting
    I can see no else for "if (iter.hasNext()) {", so if no encode is found, no error message would be displayed.

  • Convert JPanel to buffered Image

    Hi,
    i have a JPanel,I override the paintComponent() method to do a lot of painting. the size of this panel is about 2500 X 2500 i want to convert it to a buffered image,
    but i dont get image of total panel, but only the image of what is displayed on screen, every thing else is black, i guess becuase this is not painted,
    so how do i get the total image, need help
    this is my code for creating image
    JFrame frame new JFrame();
    frame.getContentPane().add(myPanel);
    this.setSize(1000,700);
    show();
    int iWidth = myPanel.getPreferredSize().width;
    int iHeight =myPanel.getPreferredSize().height;
    BufferedImage image = new BufferedImage(iWidth, iHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    myPanel.paint(g2);
    try
         ImageIO.write(image, "jpeg", new File("example.jpeg"));
    catch (Exception e) {
    e.printStackTrace();
    }Ashish

    i use this    chartPanel = new JPanel() {
          public void paint(Graphics g) {
            Image img = paintGraph(chartPanel.getWidth(), scroller.getViewport().getHeight());
            g.drawImage(img, 0, 0, Color.white, null);
      protected Image paintGraph(int width, int height) {
        if ((offscreen == null) || (width != offscreensize.width) || (height != offscreensize.height)) {
          offscreen = createImage(width, height);
          offscreensize = new Dimension(width, height);
          offgraphics = (Graphics2D)offscreen.getGraphics();
          try {
            offgraphics.setClip(0, 0, width, height);
            drawChart(offgraphics, width, height);
            offgraphics.setXORMode(offgraphics.getBackground());
            drawSelectables(offgraphics, width, height);
          } catch (ArrayIndexOutOfBoundsException e) { /* we have no data */ }
        return offscreen;
      }where scroller is my JScrollPane() and i get the complete panel to draw on.
    thomas

  • Stretch part of a buffered image

    For my dissertation at university I am writing a program to generate rectangular cartograms, for an example look at:
    here (Not my work)
    I have written the algorithm to generate the cartograms(rectangles are drawn using Java 2D rectangle) and as a further step, I have overlayed a transparent buffered image of the actual map. I want to link the image and the rectangles so that when a rectangle gets bigger, that part of the image gets stretched larger (and visa versa for a rectangle getting smaller). I can check whether rectangles are getting larger or smaller but I am not sure about how to code the stretching(distorting) of the buffered image. Any ideas (or suggestions how to do this differently) would be greatly appreciated.
    I am posting my drawing code in case this helps understand what I am trying to do. The algorithm for generating cartograms is not important and is contained in another class.
    public class DrawPanel extends JPanel
        private BufferedImage image;
         private ArrayList<Rect> newrectList;
        private ArrayList<Integer> newareaList;
        private ArrayList<ArrayList<ArrayList<Integer>>> newneighbourList;
        * Sets inherited arraylist as local variables
        * @param rectList an arraylist of Rect objects
         * @param areaList an arraylist of the desired area for each rectangle
         * @param neighbourList
         * @param transparency
         public DrawPanel(ArrayList<Rect> rectList, ArrayList<Integer> areaList,
                ArrayList<ArrayList<ArrayList<Integer>>> neighbourList,double transparency) throws IOException
            setSize(600,480);
              newrectList = rectList;
            newareaList = areaList;
            newneighbourList = neighbourList;
            float tempfloat=(float) transparency;
            image =   loadTranslucentImage(tempfloat);
        public static BufferedImage loadTranslucentImage(float transperancy) throws IOException
                // Load the image
                BufferedImage loaded = ImageIO.read(new File("Europe_map.jpg"));
                // Create the image using the
                BufferedImage aimg = new BufferedImage(loaded.getWidth(), loaded.getHeight(), BufferedImage.TRANSLUCENT);
                // Get the images graphics
                Graphics2D g = aimg.createGraphics();
                // Set the Graphics composite to Alpha
                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transperancy));
               // Draw the LOADED img into the prepared reciver image
                g.drawImage(loaded,null,0, 0);
              // let go of all system resources in this Graphics
               g.dispose();
               // Return the image
               return aimg;
        @Override
        * draws the rectangles
        * @param g A graphics object in order to draw rectangles to the screen
      //Code removed because I went over the character count
         * redraws the rectangles to the screen
        public void reDrawMap(boolean toHighlight, int highlight, boolean showPop, double transparency,
                boolean transparencyChanged) throws IOException
         Graphics g = this.getGraphics();
         g.clearRect(0,0,600,480);
         g.setColor(Color.blue);
         g.fillRect(0,0,600,480);
        int x=0;
         for(int i = 0; i < newrectList.size(); i++)
                Rect rect = newrectList.get(i);
                        int j = newareaList.get(i);
                        int area = j*j;
                       //not important                      
                g.fill3DRect(rect.x, rect.y, rect.width, rect.height,true);
                   g.setColor(Color.black);
                   g.drawString(rect.name,(rect.x)+5,(rect.y)+10);
                if(showPop == true)
                    double finalarea = area*0.005;
                    BigDecimal b = new BigDecimal(finalarea).setScale(2,BigDecimal.ROUND_HALF_UP);
                    finalarea=b.doubleValue();
                    String areastring = Double.toString(finalarea);
                    g.drawString(areastring,(rect.x)+5,(rect.y)+25);
        if(transparencyChanged ==true)
            float tempfloat=(float) transparency;
            image =   loadTranslucentImage(tempfloat);
           g.drawImage(image, 0, 0,getWidth(),getHeight(), null);
        else
            g.drawImage(image, 0, 0,getWidth(),getHeight(), null);
    }My idea is to have an arraylist of rectangles in this class to keep a local copy of the rectangles being drawn. It is then easy to test if the new rectangle being drawn has a greater or less area than previously. Once this is done, I need to execute some code to stretch a rectangle of that size and position in "image".
    Thanks,
    Matt

    I want to link the image and the rectangles so that when a rectangle gets bigger, that part of the image gets stretched larger (and visa versa for a rectangle getting smaller)Why don't you create a class that has at least these two fields
    BufferedImage country;
    Rectangle rect;Of course you can use any name for the fields you want.
    You have one universal image (in this case "Euro_map.jpg"). Country will be a subimage of this universal one
    //see BufferedImage#getSubimage api
    country = euroMap.getSubimage(x,y,w,h);then when you draw rect you draw the country on top of it scaled to fit the same bounds.
    g2d.setRenderingHint(
            java.awt.RenderingHints.KEY_INTERPOLATION,
            java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2d.setComposite(
            AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transperancy));
    g2d.drawImage(country,rect.x,rect.y,rect.width,rect.height,null);
    g2d.setComposite(AlphaComposite.SrcOver);Lastly, in your code you have this
    BufferedImage aimg = new BufferedImage(loaded.getWidth(), loaded.getHeight(), BufferedImage.TRANSLUCENT);The third parameter should be a BufferedImage type (TYPE_INT_ARGB for example). java.awt.Transparency.TRANSLUCENT has a value of 3, so you were creating a TYPE_INT_ARGB_PRE by chance. Luckily this type has an alpha channel. Were you aware you were doing that?

  • How i reduce the resolution and size or bytes of an image??

    Hi all,
    I want to reduce the size and resolution or bytes of an image?Is anyone knows the solution of my problem??
    Plzz help me out.
    Thankss

    rakhi@odm wrote: > I want to reduce the size and resolution or bytes of an image?Is anyone knows the solution of my problem?? > > Plzz help me out. That word is 'please'. It contains no 'z', let alone two of them.
    Darryl's suggestion is the best first course to reduce the image size. You might also experiment with reducing the color depth (e.g. - 64 million colors-> 256 colors/16 colors) of the images - which works particularly well for GIF (almost mandatory) or PNG - though it is relatively pointless for JPEG.
    BTW - adding dukes indicates 'interest level', but adding '4 dukes' indicates the problem is not very important. Do not expect me to make a second post on this matter unless the dukes are raised to '10' - I don't have the time.

  • Big Colour and detail changes between Original Nikon RAW files and the images created on the Preview page!

    Big Colour and detail changes between Original Nikon RAW files and the images created on the Preview page! Yes there are distinct visual changes when I preview my Nikon NEF RAW Files.Please note I do not use iPhoto at all.
    If you view it as a contact sheet straight from the original folder there are no alterations but the moment you double click and want to 'Preview' it, this new preview page introduces very noticeable distortions : lighter shading goes missing and colour goes darker e.g orange turns red and mid blue goes deep blue!  Alarmingly the little column on the left of the preview page showing the collection shows the original file colours and then after a few seconds show the new distorted image...you can see this visible change and it takes place after a few seconds once you double click! Also if you use Apple's 'Cover Flow' to preview, this function will replace your original RAW file with the new 'altered preview' image!
    I have raised this with Apple but they have yet to reply...has anyone ever experienced this? I have used my Mac book for 18months only noticed it about 5 days ago!
    I went to Apple store and we tried it in other laptops and Macs and it happened to all of them so we think this is a software issue and not down to the laptop.
    Any help is much appreciated!

    Big Colour and detail changes between Original Nikon RAW files and the images created on the Preview page! Yes there are distinct visual changes when I preview my Nikon NEF RAW Files.Please note I do not use iPhoto at all.
    If you view it as a contact sheet straight from the original folder there are no alterations but the moment you double click and want to 'Preview' it, this new preview page introduces very noticeable distortions : lighter shading goes missing and colour goes darker e.g orange turns red and mid blue goes deep blue!  Alarmingly the little column on the left of the preview page showing the collection shows the original file colours and then after a few seconds show the new distorted image...you can see this visible change and it takes place after a few seconds once you double click! Also if you use Apple's 'Cover Flow' to preview, this function will replace your original RAW file with the new 'altered preview' image!
    I have raised this with Apple but they have yet to reply...has anyone ever experienced this? I have used my Mac book for 18months only noticed it about 5 days ago!
    I went to Apple store and we tried it in other laptops and Macs and it happened to all of them so we think this is a software issue and not down to the laptop.
    Any help is much appreciated!

  • Image darker when saved than on-screen buffered image

    Hi,
    Here is my little application. I am trying to simulate an rgb screen look based on image data. ie, the new image is an exaggerated tv look of the original image.
    When I try to encode/save a jpeg from my buffered image, the saved image is darker (colours also seem to be different) than what i see in my application frame. I like what I see in the JFrame and would like to have that saved. I am just an artist hack so excuse the cobbled together code. I have also included the original image, the image as it is saved, and an image as a rough approximation of the image in the JFrame.
    In the code you will see I have tried different ways to encode the image (commented out)
    Any ideas about this issue or how to make this program more sound please let me know.
    the code:
    http://zukanter.com/javaImageTest/displayImageRGBBuffer.java
    the orignal loaded into the appp:
    http://zukanter.com/javaImageTest/myPic.jpg
    the saved image:
    http://zukanter.com/javaImageTest/_003.jpeg
    the image as it is in the application window:
    http://zukanter.com/javaImageTest/_003Screen.jpg

    Hi
    My 2c.
    I`ve had a quick look at your code and the output and I`m assuming that the vertical RGB lines are what you intended.
    Jpeg works in blocks, and averages pixel valiues across them.
    If introducing those primaries into the graphic and then compressing it makes it darker that`s likely the result of the primary colours being averaged by the compression algorithm.
    You should look at resizing the image first, drawing it onto an offscreen buffer, then doing an overlay (alpha channel) with the primary colors instead, IMHO.
    regards

  • Lightroom 5 will not read my Raw preview files no images in preview file to copy

    lightroom 5 will not read my RAW preview file , no images in preview file to copy.instead of image file states , preview file unavailable for this file

    alvinc wrote:
    lightroom 5 will not read my RAW preview file , no images in preview file to copy.instead of image file states , preview file unavailable for this file
    Hi,
    Please provide more information ... such as:
    - What are you trying to do? e.g. "Trying to import images from CF Card I get this message"
    - What PC are you using? e.g. "Mac, PC, memory etc"
    It is quite a cryptic thread but it sounds like you are trying to import directly from a CF Card, if you are copy the images to the hard disk then import.

Maybe you are looking for

  • How can i remove "A newer version of the app" pop up

    I keep getting the following pop up message everytime i open iTunes or download a song. "A newer version of the app "APP NAME SHOWN HERE" already exists in your iTunes Library. Are you sure you want to replace it with the one you are moving?" Its rea

  • Configuration Issue in connecting oracle AQ in weblogic server 10.3.5

    Hi, I am working in Message driven bean and want to receive the message from queue called IEDWM_QUEUE and have made all the necessary configurations for connecting oracle AQ in weblogic .... Created Foriegnserver,connections factories,destination in

  • Startx from tmux

    Hello! I'd like to start a tmux session on every login, so I put what the wiki suggests in my .zshrc and it works as aspected. But everytime I try to startx as normal user from there, Xorg fails with this output: Fatal server error: (EE) xf86OpenCons

  • My Illustrator CS5 freezes when I open the programme or a file

    I have a MacBook Pro 5 with Mac OS X 10.6.8, I use Adobe MasterSuite CS5, although the only programs fully installed from it are Photoshop, Illustrator, InDesign and Flash. I rarely use Flash, but rely on the other three heavily for work. I opened an

  • Report that can take the system: (users, utilization, T-CODE)

    I need a report that can take the system: How many times a user logged into the system in the last month Most used transactions Changes passwords. Etc., all you have to do with a user-level tuning. thanks, VLopes