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?

Similar Messages

  • How can I allow a user (client) to choose a local image file (on his hard d

    How can I allow a user (client) to choose a local image file (on his hard drive) and modify it using an applet from his browser ? I am trying to develop a web page that enables the user to choose an Image file, manipulate the image using a java applet, and display the results.
    Using Java�s �JFileChooser� does not work when called from a browser, probably due to security privileges issues. On the other hand, I can choose and upload any file using a JavaScript form:
    <FORM METHOD="POST" ENCTYPE="multipart/form-data" ACTION="process.asp">
    <INPUT TYPE=FILE NAME="file1"><BR>

    It seems that I can choose an image file with a Java script form and process an image with an applet. How can I choose a file AND process it locally ?
    (I do not wish to upload the file to the server using JavaScript form and then back to the client�s applet for processing since it will be a tremendous waste of resources).
    Will appreciate any solution.
    Thanks !
    ( my email is: [email protected] )

    "Using Java�s �JFileChooser� does not work when called from a browser, probably due to security privileges issues. "
    You can do this if you sign the applet...

  • How to save Buffered Image with variable transparency in a file.

    Hi,
    I need to save BufferedImage (type ARGB) in a file.
    Transparency in this image is a function of position. Who knows, what would be the best suggestion for type of file to store this image (probably not JPEG) and which package would be appropriate. A sample of code would be higly desirable. Please help, thank you in advance.

    Your can use the ImageIO-API if your software runs under JVM1.4 or you must use the JAI (Advanced Imaging API) ...

  • 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 Component for JavaFX not available?

    Is there a way to have a “File Chooser Component” for JavaFX Applications?
    Netbeans IDE offers a “Palette Swing Windows” Components, displays such item, but I am unable to put it into my FX Script.
    Any workaround? or miss I a anything?
    I want to pickup any sourcefile: "{__DIR__}sound/{soundName}" from local disc and run it on a Mediaplayer

    import javax.swing.filechooser.FileFilter;
    * @author Pawel
    public class OpenFileFilter extends FileFilter {
        override public function getDescription() : String {
            return "all movies";
        override public function accept(f: java.io.File) : Boolean {
            return f.isDirectory()
                or f.getName().endsWith(".avi")
                or f.getName().endsWith(".mov")
                or f.getName().endsWith(".flv");
    import java.awt.SystemTray;
    import java.awt.TrayIcon;
    import java.awt.Toolkit;
    import java.awt.PopupMenu;
    import java.awt.MenuItem;
    import java.awt.AWTException;
    import java.lang.System;
    var stage : Stage = Stage {
        title: "JavaWars"
        width: 800
        height: 600
        scene: scene,
        style: StageStyle.TRANSPARENT,
        extensions: [
            AppletStageExtension {
                shouldDragStart: function(e): Boolean {
                    return inBrowser and e.primaryButtonDown and header.hover;
                onDragStarted: function() {
                    inBrowser = false;
                    addTray();
                onAppletRestored: function() {
                    inBrowser = true;
                    removeTray();
                useDefaultClose: true
    var trayIcon : TrayIcon;
    function addTray() : Void{
        if(SystemTray.isSupported()) {
            var tray : SystemTray  = SystemTray.getSystemTray();
            var image : java.awt.Image = Toolkit.getDefaultToolkit().getImage("{__DIR__}resources/images/trayicon.png");
            var popup : PopupMenu = new PopupMenu();
            var item : MenuItem = new MenuItem("Zako&#324;cz");
            item.addActionListener(ActionListener{
                override public function actionPerformed(e : ActionEvent): Void {
                    var tray : SystemTray  = SystemTray.getSystemTray();
                    tray.remove(trayIcon);
                    stage.close();
            popup.add(item);
            trayIcon = new TrayIcon(image, "kliknij prawym, aby zamkna&#263; aplikacj&#281;", popup);
            try {
                tray.add(trayIcon);
            } catch (e : AWTException) {
                System.err.println("Can't add to tray");
        } else {
            System.err.println("Tray unavailable");
    function removeTray() : Void{
        if(SystemTray.isSupported()) {
            var tray : SystemTray  = SystemTray.getSystemTray();
            try {
                tray.remove(trayIcon);
            } catch (e : AWTException) {
                System.err.println("Can't remove tryicon");
    }

  • 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

  • Combining File Chooser and this MP3 class

    Hello all,
    I was curious if anyone could help me figure out how to get a file to actually load once it is used with this code.
    I'm unfamiliar with how it works and I was hoping for an explanation on it.
    I wasn't sure if I had to have the program recgonize that I would like to load a mp3 or if it just would load it automatically...
    Essentially, I want to be able to load a mp3 if I use the file chooser.
    I can try to clarify my question more if anyone should need it.
    Thank you
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class List extends JPanel
                                 implements ActionListener {
        static private final String newline = "\n";
        JButton openButton, saveButton;
        JTextArea log;
        JFileChooser fc;
        public List() {
            super(new BorderLayout());
            //Create the log first, because the action listeners
            //need to refer to it.
            log = new JTextArea(5,20);
            log.setMargin(new Insets(5,5,5,5));
            log.setEditable(false);
            JScrollPane logScrollPane = new JScrollPane(log);
            //Create a file chooser
            fc = new JFileChooser();
            //Uncomment one of the following lines to try a different
            //file selection mode.  The first allows just directories
            //to be selected (and, at least in the Java look and feel,
            //shown).  The second allows both files and directories
            //to be selected.  If you leave these lines commented out,
            //then the default mode (FILES_ONLY) will be used.
            //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
           // fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            //Create the open button.  We use the image from the JLF
            //Graphics Repository (but we extracted it from the jar).
            openButton = new JButton("Open a File...",
                                     createImageIcon("images/Open16.gif"));
            openButton.addActionListener(this);
            //Create the save button.  We use the image from the JLF
            //Graphics Repository (but we extracted it from the jar).
            saveButton = new JButton("Save a File...",
                                     createImageIcon("images/Save16.gif"));
            saveButton.addActionListener(this);
            //For layout purposes, put the buttons in a separate panel
            JPanel buttonPanel = new JPanel(); //use FlowLayout
            buttonPanel.add(openButton);
            buttonPanel.add(saveButton);
            //Add the buttons and the log to this panel.
            add(buttonPanel, BorderLayout.PAGE_START);
            add(logScrollPane, BorderLayout.CENTER);
        public void actionPerformed(ActionEvent e) {
            //Handle open button action.
            if (e.getSource() == openButton) {
                int returnVal = fc.showOpenDialog(List.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                    //This is where a real application would open the file.
                    log.append("Opening: " + file.getName() + "." + newline);
                } else {
                    log.append("Open command cancelled by user." + newline);
                log.setCaretPosition(log.getDocument().getLength());
            //Handle save button action.
            } else if (e.getSource() == saveButton) {
                int returnVal = fc.showSaveDialog(List.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                    //This is where a real application would save the file.
                    log.append("Saving: " + file.getName() + "." + newline);
                } else {
                    log.append("Save command cancelled by user." + newline);
                log.setCaretPosition(log.getDocument().getLength());
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path) {
            java.net.URL imgURL = List.class.getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("FileChooserDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new List();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }The mp3 class that I've been playing around with...
    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    import javazoom.jl.player.Player;
    public class MP3 {
        private String filename;
        private Player player;
        // constructor that takes the name of an MP3 file
        public MP3(String filename) {
            this.filename = filename;
        public void close() { if (player != null) player.close(); }
        // play the MP3 file to the sound card
        public void play() {
            try {
                FileInputStream fis = new FileInputStream(filename);
                BufferedInputStream bis = new BufferedInputStream(fis);
                player = new Player(bis);
            catch (Exception e) {
                System.out.println("Problem playing file " + filename);
                System.out.println(e);
            // run in new thread to play in background
            new Thread() {
                public void run() {
                    try { player.play(); }
                    catch (Exception e) { System.out.println(e); }
            }.start();
    // test client
        public static void main(String[] args) {
            String filename = "C:\\FP\\1.mp3";
            MP3 mp3 = new MP3(filename);
            mp3.play();
    }

    Thanks for the link
    I've been looking over the sections and still confused with the code.
    It's obvious that I have to do something with this portion of the code:
    public void actionPerformed(ActionEvent e) {
        //Handle open button action.
        if (e.getSource() == openButton) {
            int returnVal = fc.showOpenDialog(FileChooserDemo.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                //This is where a real application would open the file.
                log.append("Opening: " + file.getName() + "." + newline);
            } else {
                log.append("Open command cancelled by user." + newline);
    }I'm just not sure what.

  • 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?

  • Save image to a file got a blank image.

    I need to save graphics image of a component to a file. Following is what I did.
    1. Call createImage() from this component.
    2. Convert the image to a BufferedImage.
    3. Call ImageIO.write() to save it in a file.
    What I got from the result file is all blank. Following is the code.
    Please help. Thanks a lot!
    import java.io.*;
    import java.awt.*;
    import java.awt.image.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class SaveLabelImage
         String jpg_out = "image.jpg";
         String dir_name = "c:\\temp\\";
         SaveLabelImage()
              // Use a label to display some text
              JFrame frame = new JFrame();
              JLabel label = new JLabel( "ABCDEFG", JLabel.CENTER );
              Container contentPane = frame.getContentPane();
              contentPane.add( label, BorderLayout.CENTER );
              frame.setSize( 300, 150 );
              frame.setVisible(true);
              File f_dir = new File( dir_name );
              if ( !f_dir.exists() ) f_dir.mkdir();          
              write_label( label, jpg_out );
    public void write_label( JLabel label, String out_fn )
              // Save the image to a file
              int w = label.getWidth();
              int h = label.getHeight();
              Image im = (Image)label.createImage( w, h );
              BufferedImage bimage = new BufferedImage( w, h, BufferedImage.TYPE_INT_RGB );     
              Graphics2D g2 = bimage.createGraphics();     
              g2.drawImage( im, null, null );                                             
              if ( bimage == null ) {
                   System.out.println( "Buffered Image is null!" );
                   return;
              try
                   String fn = dir_name + jpg_out;
                   File file = new File( fn );
    ImageIO.write( bimage, "jpg", file );          
                   System.out.println( "Image of Jlabel is saved in file " + fn );
              catch (IOException e) {;    }
         }     //write_label
         public static void main(String arg[])
              new SaveLabelImage() ;               
    }     // class SaveLabelImage

    I am able to get a good image file now. Thanks you very much.
    However I still have a few quesions.
    1. In my case, the label is visible on the screen, why I need to call the setVisible(true) again?
    2. Why use print() instead of paint()?
    3. I have to use BufferedImage.TYPE_INT_ARGB to create a new BufferedImage, otherwise the result image file is in black.
    4. I did not use the hints because it is very confusing. Fortunately, It worked without them.
    Following is a modified version of your code.
    import java.io.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.image.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class SaveComponentAsImage
    public static void saveComponentAsImage(
                             JComponent c,
                             int w, int h, int image_type,
                             String fn, String file_type )
              c.setSize(w, h);
    c.setVisible(true);
    c.validate();
    // use TYPE_INT_ARGB if you want alpha (transparency)
    BufferedImage image = new BufferedImage( w, h, image_type );
    Graphics g = image.getGraphics();
    // draw the graphics
    c.print(g);
    g.drawLine(0,0, c.getWidth(),c.getHeight());
    // write it out
    try {
    ImageIO.write(image, file_type, new File(fn));
    System.out.println( "Image is saved in file " + fn );
    } catch (IOException ioe) {
    System.out.println(ioe.getMessage());
    // cleanup
    g.dispose();
         public static void main(String arg[])
              JLabel l = new JLabel( "ABCDEFG", JLabel.CENTER );
              int w = l.getWidth();
              int h = l.getHeight();
              System.out.println( "label width=" + w );
              System.out.println( "label height=" + h );
              if ( w == 0 || h == 0 )
                   w = l.getPreferredSize().width;
                   h = l.getPreferredSize().height;
              System.out.println( "Preffered width=" + w );
              System.out.println( "Preffered height=" + h );          
              w +=100;
              h +=50;          
              String fn = "myImage.png";
              int image_type = BufferedImage.TYPE_INT_RGB;          
              saveComponentAsImage( (JComponent)l, w, h, image_type, fn, "png" ) ;     
              image_type = BufferedImage.TYPE_INT_ARGB;     
              fn = "myImage_ARGB.png";                                   
              saveComponentAsImage( (JComponent)l, w, h, image_type, fn, "png" ) ;     
    }

  • File Chooser in Flex

    I want to make a file chooser that can allow me to choose
    (Browse) where's the file that i want to upload. Anyone know how to
    create a file chooser with flex builder 2 ? I'm very appreciate for
    any answer.

    Here is an example that will make a file browser to choose
    either an image or mp3 file:
    private var upload_ref:FileReference;
    private function upload_media():void {
    var media_filter:FileFilter;
    var filter_array:Array = new Array();
    media_filter = new FileFilter("Images (*.jpg, *.jpeg, *.gif,
    *.png)", "*.jpg; *.jpeg; *.gif; *.png");
    filter_array.push(media_filter);
    media_filter = new FileFilter("Audio (*.mp3)", "*.mp3");
    filter_array.push(media_filter);
    upload_ref = new FileReference();
    upload_ref.browse(filter_array);
    upload_ref.addEventListener(Event.SELECT, file_selected);
    private function file_selected(evt:Event):void {
    if (upload_ref.name != null &&
    upload_ref.name.search(" ") == -1 &&
    upload_ref.name.search("'") == -1) {
    var sendVars:URLVariables = new URLVariables();
    sendVars.file_path = "/path_on_server_to_upload_to";
    var request:URLRequest = new URLRequest();
    request.url = "
    http://yourserver.com/upload_php_script.php";
    request.data = sendVars;
    request.method = URLRequestMethod.POST;
    upload_ref.addEventListener(Event.COMPLETE, completeUpload);
    upload_ref.upload(request);
    } else {
    Alert.show("File name can only include letters, numbers or
    underbars. No spaces.");
    Vygo

  • Converting an image to a buffered image

    is there a faster way to convert an image into a buffered image. Ive looked around and the general solution is:
    BufferedImage bi = new BufferedImage(image.getWidth(), image.getHeight(),
    BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics();
    g.drawImage(image, 0, 0, null);
    but that loads up 2 different varibles, g and bi, and this is going to be going in a loop. im under the impression 2 varibles is gonna slow it down, and the more fps i can get the better. I saw something about ImageIO, but from what i could gather that had to use url or stored file, rather than a Image type varible. whats the fastest whay to get a buffered image from an image. thx

    Presumably you are loading the image from a file or something.
    Why don't you load it directly into a buffered image using ImageIO? All you need to write is
    import javax.imageio.ImageIO;
    BufferedImage image = ImageIO.read(parameters...);
    there are several overloads, check the definitions here http://java.sun.com/j2se/1.5.0/docs/api/javax/imageio/ImageIO.html

  • Getting pixxels in a buffered image?

    Hi, I want write a string to a buffered image, then iterate through the pixels. I've tried something like the following:
    BufferedImage bi = new BufferedImage( 1000 , 1000 , BufferedImage.TYPE_BYTE_GRAY);
    Graphics2D g = bi.createGraphics();
    File file = new File("C:\\Windows\\Fonts\\verdana.ttf");
    FileInputStream fis = new FileInputStream(file);
    Font font = Font.createFont(Font.TRUETYPE_FONT, fis);
    font = font.deriveFont(30.0f);
    g.setFont(font);
    g.drawString( "m" , 0 , 0);
    Rectangle2D bounds = font.getStringBounds( "m" , g.getFontRenderContext());
    Raster r = bi.getData( new Rectangle( 0 , 0 , (int)bounds.getWidth() , (int)bounds.getHeight() ));
    for ( int i=0 ; i < r.getHeight() ; i++ ){
    System.out.print( i + ":");
    for ( int j=0 ; j< r.getWidth() ; j++ ){
    System.out.print( r.getPixel( i , j , new double[]{0} )[0] );
    System.out.println();
    But,I think at a high level I might be barking up the wrong tree (the output is all just a bunch of zeros, and around the 29th itteration of the outer loop it just throws an exception.
    Pointers in the appropriate direction?
    Thanks in advance...

    Just for overkill...
    You can also use ImageIO to read in the GIF image; that will return
    you a BufferedImage that has the transparency data (and everything else)
    intact.
    And you can create a BufferedImage with transparency indirectly by
    using:
    GraphicsConfiguration.createCompatibleImage(w, h, transparency)
    with a transparency value of Transparency.BITMASK).
    You should then be able to request a Graphics of that image and
    draw into it from the GIF image.
    Chet.
    (Java2D team)

  • A generic error occurred in GDI+ while assing tiff image file to Bitmap and Image

    Hi,
    I am getting "A generic error occurred in GDI+" error while reading the tiff image file to Bitmap or Image.
    Below is my sample code.
    string filePath=@"c:\Images\sample.tif";
    Bitmap bmp=new Bitmap(filePath);   // here getting exception
    int totalpages=bmp.GetFrameCount(.....);
    etc......
    I tried using Bitmap.FromFile() and also from FromStream() even for Image also but there is no use.
    Moreover i m having full permissions for the file path and the tiff file is having multiple pages.
    Can anyone help me to solve this issue please.
    Thanks & Regards,
    Kishore
    Kishore

    Make sure that the Tif file is valid (can other software open it)?  If you are able to save a Tif using GDI+, try saving that Tif, then opening it.  Part of me wonders if there is something about that specific Tif that GDI+ doesn't like.
    You could also try using WIC to open the TIF, perhaps you would have better luck there.

  • 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

Maybe you are looking for

  • Sql server replication from SQL SERVER VERSION(7.0) to SQL SERVER 2005

    Hi All, We are trying to create a replication between Sql server 7.0 data to SQL server 2005 data . We tried to create a local subscription in Sql server ,when tried to connect to publisher  running in Sql server 7.0 it is showing an error message li

  • How to determine which SUS Scenario my company is using?

    Hello, How can I quickly determine which SUS Scenario my company is using?  Is this a configuration option in SPRO?  We are using ECC to create PO -> IDOC-XML -> PI -> Proxy -> SUS SUS creates PO Confirmation, ASN, Invoice response documents to ECC.

  • Suddenly iDVD won't burn a disk

    I use iDVD a lot. I'm a pro photographer and I love it for showing off work to clients. I have a disk that I definitely, absolutely ned to get out of the door today and for the first time ever I hav problems with it. The burn gets all the way to the

  • Samsung 6400 LED TV, 2nd Generation Apple TV, HDMI, only 780...

    I have a 2nd generation apple TV connected to my brand new Samsung 6400 LED via HDMI and am only getting 780 screen resolution.  My other devices, all connected via HDMI, are showing in 1080.  I have a 1st gen apple TV in my bedroom, connected to a s

  • Can't open FF. Says "firefox.exe is not a valid Win32 application."

    When I click the Mozilla desktop icon, I hear a "beep," and the pop-up with a red "X" says... "firefox.exe is not a valid Win32 application." That's as far as I get.