Write an imageIcon or buffered image to file (or to system clipboard)

hi all,
I just want to write an imageIcon to file, or a bufferedImage. Anyone have any ideas. Or pointers of where to start?

Hi,
To save a BufferedImage you could use the javax.imageio api :
try {
  ImageIO.write(image, "JPEG", new File(myFileName));
} catch (IOException e) {
   e.printStackTrace();
}That's it !
And to read a BufferedImage it the about the same thing.
Happy new year,
Jean-Paul

Similar Messages

  • Imageicon to buffered image

    how to convert imnage icon to bufferedimage

    Perhaps the best thing to do is make sure you start with a BufferedImage, and create the ImageIcon from that.
    If that is out of your control, an ImageIcon has-a Image, which, if getImageLoadStatus is COMPLETE, is
    guaranteed to be loaded into memory (the other status options are ERRORED or ABORTED). If that Image
    is not also a BufferedImage, you'll have to create a BufferedImage out of a plain, loaded Image: construct
    a BufferedImage of the appropriate dimensions, and draw the original image onto its Graphics object.

  • 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 write an ImageIcon to file?

    I would like to write an ImageIcon, or meaby another kind of image to a file.
    I'vet tried it this way:
    FileOutputStream fileOutput = new FileOutputStream("C:\\Documents and Settings\\Stijn\\Mijn documenten\\test\\test.jpg");
    ObjectOutputStream objOutput = new ObjectOutputStream(fileOutput);
    objOutput.writeObject(imageIcon);
    objOutput.close();
    fileOutput.close();but this didn't work.

    nobody any ideas?

  • 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

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

  • How I may convert image to file?

    may previusly problem is join with   BufferedImage bimage = ImageIO.read(file); whose I not use previusly
    I may convert image file from filter to file '

    File imageFile = new File("myImage");
    try
        // img is your buffered image
        // screenshotType is "png", "jpg", "tif", "bmp"
        ImageIO.write(img, screenshotType, imageFile);
    catch(IOException e)
        System.out.println("IO Error while trying to save image file");
    }Edited by: Nighttime on Feb 9, 2008 5:50 PM

  • What is my Image source file

    Hello,
    I wrote a piece if Java programm that looks like:
    bgFile="MyImageSourceFile.gif";
    Image bgImage = Toolkit.getDefaultToolkit().getImage(bgFile);
    final ImageIcon bgIcon = new ImageIcon(bgImage);
    bgLabel = new JLabel(bgIcon);
    MyLayerdPane.add(bgLabel, new Integer(0)); //low layer
    jTabbedPane1.add(MyLayerdPane,1);
    Later on I want to get the filename of that image back again.
    I tried:
    javax.swing.JLayeredPane LayPn = (javax.swing.JLayeredPane) jTabbedPane1.getComponentAt(1);
    Component[] Cmp = (Component[]) LayPn.getComponentsInLayer(0);
    JLabel Lbl = (JLabel) Cmp[0];
    ImageIcon ImgIcn =(ImageIcon) Lbl.getIcon();
    Image ThisImage = ImgIcn.getImage();
    I can see with the dubbugger that the source of the image is indeed "MyImageSourceFile.gif", but how can I print this name to a file, like THE_SOURCE="MyImageSourceFile.gif"?

    Simply write Lbl.getIcon().toString() in your file...

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

  • How to save an image to file without rendering to screen?

    Does anyone know of a way I can save a buffered image to a file (as a jpg) without having to render it to a screen first? I can create the file fine if I place the image on a JPanel first. However when I try to save the image directly to a file, the program hangs when I try to render the image to a Graphics object. Is there some sort of initialisation carried out on the image when it is displayed on screen which I need to carry out to save the image offscreen?
    Just as a background, what I am trying to achieve is to create a chart (using Monarch Charts library) based on a supplied set of data, and then to save this chart as a jpg. It works fine if I first display the chart in a JPanel but not when I try to save it offscreen.
    Can anyone help me out here?
    Thanks,
    Ciaran

    Here's the code I use in JFreeChart to create a buffered image - the third line draws the chart using the Graphics2D obtained from the BufferedImage:
        public BufferedImage createBufferedImage(int width, int height) {
            BufferedImage image = new BufferedImage(width , height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            this.draw(g2, new Rectangle2D.Double(0, 0, width, height), null);
            g2.dispose();
            return image;
        }Writing to a JPEG can be done like this (method taken from the ChartUtilities class in JFreeChart):
        public static void writeChartAsJPEG(OutputStream out, JFreeChart chart, int width, int height)
            throws IOException {
            BufferedImage image = chart.createBufferedImage(width, height);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
            param.setQuality(1.0f, true);
            encoder.encode(image, param);
        }If you want to try some running code, download JFreeChart from:
    http://www.object-refinery.com/jfreechart/index.html
    ...then run this application:
    package com.jrefinery.chart.demo;
    import java.io.File;
    import com.jrefinery.chart.JFreeChart;
    import com.jrefinery.chart.ChartFactory;
    import com.jrefinery.chart.ChartUtilities;
    import com.jrefinery.chart.demo.DemoDatasetFactory;
    import com.jrefinery.data.XYDataset;
    public class ChartToFile {
        public static void main(String[] args) {
            XYDataset data = DemoDatasetFactory.createTimeSeriesCollection2();
            JFreeChart chart = ChartFactory.createTimeSeriesChart("Sample Chart", "Time", "Rate", data, true);
            File file = new File("MyChart.jpg");
            try {
                ChartUtilities.saveChartAsJPEG(file, chart, 400, 300);
            catch (java.io.IOException e) {
                System.out.println(e.getMessage());
    }Regards,
    Dave Gilbert
    www.object-refinery.com

  • How do I write a CD as an image?

    This may not be in the right forum but I was wondering how to write a disc as an image and not a data file?
    I am trying to update my Sony Bluray player firmware and have an ISO file that I need to burn on a CD as an image and I don't see an option to do that with the mac. Do I need a special program?
    THX

    open disk utility drag your disk image to the disk utility window, select it there and click "burn" in the toolbar. that's how it works with regular disk images. not sure about ISO files but you can try.

  • Save byte array (image) to file with servlet

    Good day.
    I should must to save a png image to file.
    I have a byte array of the image.
    This work is in a servlet.
    How can I do it?
    Best regards.
    Stefano Errani

    Good day.
    I have a byte[] and then I have used
    FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath("/public_html/mcfoto/foto1.png"));
    fos.write(bt, 0, bt.length); // byte[] bt
    fos.close();
    This on my web server that has public_html as root web directory.
    The server is in multi domain.
    In this mode I have an error.
    Then I have tryied to use
    FileOutputStream fos = new FileOutputStream("http://www.stefanoerrani.it/mcfoto/foto1.png");
    and
    FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath("http://www.stefanoerrani.it/mcfoto/foto1.png"));
    In both ways I have obtained an error.
    At last I have tryied in my localhost (local machine) using
    FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath("/mcfoto/foto1.png"));
    All run correclty.
    The Application Server is Tomcat with Apache HTTP Server.
    The first server (of www.stefanoerrani.it) has Linux as OS.
    My local server has Windows as OS.
    I should want, if it's possible, an help.
    Best regards.
    Stefano Errani

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

Maybe you are looking for