ImageIO, BufferedImage and PNG

Hello,
I have a BufferedImage object, and I would like to copied it to the clipboard as a PNG image. What I have now is a code that copy the BufferedImage to the clipboard.
What's the best way to convert the BufferedImage to PNG? There is ImageIO.write() but I would prefer to not create a file on the disk for this task.
Is it possible to create file in memory? or is it possible to convert the image in memory?
Thanks in advance for your help.

Thanks all for your answers.
I found one possibility : an array of byte can be converted to an Image with a call to Toolkit.getDefaultToolkit().createImage()
So the code looks like this:
BufferedImage img = /* some code to get the img */;
ByteArrayOutputStream byteoutarray = new ByteArrayOutputStream();
ImageIO.write(img, "png", byteoutarray);
PngSelection trans = new PngSelection(byteoutarray.toByteArray());
Clipboard clipboard = getToolkit().getSystemClipboard();
clipboard.setContents(trans, null);where PngSelection is defined like this:
public static class PngSelection
   implements Transferable
   private byte[] data;
   public PngSelection(byte[] data) {
     this.data = data;
   public DataFlavor[] getTransferDataFlavors()
     return new DataFlavor[] {DataFlavor.imageFlavor};
   public boolean isDataFlavorSupported(DataFlavor flavor)
     return DataFlavor.imageFlavor.equals(flavor);
   public Object getTransferData(DataFlavor flavor)
     throws UnsupportedFlavorException,IOException
     if (!DataFlavor.imageFlavor.equals(flavor))
       throw new UnsupportedFlavorException(flavor);
     return Toolkit.getDefaultToolkit().createImage(data);
  }I need to test all this but it seems to works. Thanks again.

Similar Messages

  • Memory Efficiency of BufferedImage and ImageIO

    This thread discusses the memory efficiency of BufferedImage and ImageIO. I also like to know whether if there's possible memory leak in BufferedImage / ImageIO, or just that the result matches the specifications. Any comments are welcomed.
    My project uses a servlet to create appropriate image tiles (in PNG format) that fits the specification of google map, from images stored in a database. But it only takes a few images to make the system out of heap memory. Increasing the initial heap memory just delays the problem. So it is not acceptable.
    To understand why that happens, I write a simple code to check the memory usage of BufferedImage and ImageIO. The code simply keeps making byte arrays from the same image until it is running out of the heap memory.
    Below shows how many byte arrays it can create:
    1M jpeg picture (2560*1920):
    jpeg = 123
    png = 3
    318K png picture (1000*900):
    jpeg = 1420
    png = 178
    Notice that the program runs out of memory with only 3 PNG byte arrays for the first picture!!!! Is this normal???
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    import javax.imageio.*;
    import java.io.*;
    import javax.swing.*;
    import java.util.*;
    public class Test {
         public static void main(String[] args) {
              Collection images = new ArrayList();
              for (;;) {
                   try {
                        BufferedImage img = ImageIO.read(new File("PTHNWIDE.png"));
                        img.flush();
                        ByteArrayOutputStream out =
                             new ByteArrayOutputStream();
                        ImageIO.write(img, "png", out); // change to "jpeg" for jpeg
                        images.add(out.toByteArray());
                        out.close();
                   } catch (OutOfMemoryError ome) {
                        System.err.println(images.size());
                        throw ome;
                   } catch (Exception exc) {
                        exc.printStackTrace();
                        System.err.println(images.size());
    }

    a_silent_lamb wrote:
    1. For the testing program, I just use the default VM setting, ie. 64M memory so it can run out faster. For server, the memory would be at least 256M.You might want to increase the heap size.
    2. Do you mean it's 2560*1920*24bits when loaded? Of course.
    That's pretty (too) large for my server usage, Well you have lots of image data
    because it will need to process large dimension pictures (splitting each into set of 256*256 images). Anyway to be more efficient?Sure, use less colors :)

  • BufferedImage from PNG : Alpha Channel disregaurded

    I'm trying to load a PNG with an alpha channel into a BufferedImage, and
    then sample the BufferedImage at various pixels for some operations.
    However, the alpha channel seems to get lost upon creation of the BufferedImage.
    For example, I'm using a PNG that is 100% transparent, and when I
    load it into a BufferedImage and display it on a panel all I see is the panel's background color.
    So far so good. Now, the problem. When I try to sample a pixel, the alpha is always 255 or 100% opaque
    which is clearly not right. Also, when I print out the BufferedImage's type, I get 0 which means the image
    type is "Custom". Care to shed any light as to how I can accurately sample an image with an alpha channel?
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import javax.imageio.*;
    import java.awt.image.*;
    public class PNGTest extends JFrame {
        public PNGTest() {
            setLocation(500,500);
            BufferedImage img = new BufferedImage(640,480,BufferedImage.TYPE_INT_RGB);
            try {
                img = ImageIO.read(new File("C:/folder/folder/myPNG.png"));
            } catch (Exception e) {
            setSize(img.getWidth(), img.getHeight());
            getContentPane().setBackground(Color.white);
            getContentPane().add(new JLabel(new ImageIcon(img)));
            setVisible(true);
            //Sample top left pixel of image and pass it to a new color
            Color color = new Color(img.getRGB(0,0));
            //print the alpha of the color
            System.out.println(color.getAlpha());
            //print the type of the bufferedimage
            System.out.println(img.getType());
        public static void main(String[] args) {
            new PNGTest();
    }Edited by: robbie.26 on May 20, 2010 4:26 PM
    Edited by: robbie.26 on May 20, 2010 4:26 PM
    Edited by: robbie.26 on May 20, 2010 4:29 PM

    Here ya go robbie, ti seems to work for the rest of the world, but not for you:
    import java.awt.*;
    import java.awt.image.*;
    import java.net.URL;
    import javax.swing.*;
    import javax.imageio.*;
    public class JTransPix{
      JTransPix(){
        JFrame f = new JFrame("Forum Junk");
        JPanel p = new MyJPanel();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(p);
        f.pack();
        f.setVisible(true);
      public static void main(String[] args) {
        new JTransPix();
      class MyJPanel extends JPanel{
        BufferedImage bi = null;
        MyJPanel(){
          try{
            bi = ImageIO.read(new URL("http://upload.wikimedia.org/wikipedia/commons/archive/4/47/20100130232511!PNG_transparency_demonstration_1.png"));  //here ya go--one liner
            this.setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
          }catch(java.io.IOException e){
            System.out.println(e.toString());
        public void paintComponent(Graphics g){
          super.paintComponent(g);
          g.setColor(Color.BLUE);
          g.fillRect(0, 0, bi.getWidth(), bi.getHeight());
          g.drawImage(bi,0, 0, this);
    }Please notice how the BufferedImage is declared and set to NULL, then allow ImageIO to set the type--Just as I said before. If you have any question about the PNG producing an ARGB image with ImageIO, then change the color painted onto the backgroun din the paintComponent to what ever you want and you'll see it show through.
    BTW: even in the short nobrainers--you still need to have VALID CATCH BLOCKS.
    To get what you are looking for, you can mask off the Alpha component by dividing each getRGB by 16777216 (256^3) or do a binary shift right 24 places.

  • Converting transparent GIF and PNG to JPEG

    Hi,
    I have been reading in various sample gifs and png files and converting them to jpeg via javax.imageio.
    This works fine if there is no transparency colour defined in the png or gif file. But if it has a transparency colour, the resulting jpeg is messed up. Now, it appears the reason is because jpeg has no transparencies. So, my question is, how does one get rid of the transparency (assuming I want to convert it to 'white')?
    For the record, I am calling
    BufferedImage image= reader.read(0);Where reader is an ImageReader and I then convert "image" to jpeg.

    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class LoseTransparency {
        public static void main(String[] args) throws IOException {
            URL url = new URL("http://java.sun.com/docs/books/tutorial/figures/uiswing/components/ButtonDemoFiles.gif");
            BufferedImage bi1 = ImageIO.read(url);
            int w = bi1.getWidth();
            int h = bi1.getHeight();
            BufferedImage bi2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bi2.createGraphics();
            g.setColor(Color.WHITE);
            g.fillRect(0,0,w,h);
            g.drawRenderedImage(bi1, null);
            g.dispose();
            JPanel p = new JPanel(new GridLayout(2,1));
            p.setBackground(Color.YELLOW);
            p.add(new JLabel(new ImageIcon(bi1)));
            p.add(new JLabel(new ImageIcon(bi2)));
            final JFrame f = new JFrame("LoseTransparency");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(p);
            f.pack();
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }

  • ImageIO: scaling and then saving to JPEG yields wrong colors

    Hi,
    when saving a scaled image to JPEG the colors are wrong (not just inverted) when viewing the file in an external viewer (e.g. Windows Image Viewer or The GIMP). Here's the example code:
    public class Main {
         public static void main(String[] args) {
              if (args.length < 2) {
                   System.out.println("Usage: app [input] [output]");
                   return;
              try {
                   BufferedImage image = ImageIO.read (new File(args[0]));
                   AffineTransform xform = new AffineTransform();
                   xform.scale(0.5, 0.5);
                   AffineTransformOp op = new AffineTransformOp (xform, AffineTransformOp.TYPE_BILINEAR);
                   BufferedImage out = op.filter(image,null);
                   ImageIO.write(out, "jpg", new File(args[1]));
    /* The following ImageViewer is a JComponent displaying
    the buffered image - commented out for simplicity */
                   ImageViewer imageViewer = new ImageViewer();
                   imageViewer.setImage (ImageIO.read (new File(args[1])));
                   imageViewer.setVisible (true);
              catch (Exception ex) {
                   ex.printStackTrace();
    Observations:
    * viewing this JPEG in an external viewer displays the colors wrong, blue becomes reddish, skin color becomes brown, blue becomes greenish etc.
    * when I skip the transformation and simply write the input 'image' instead the colors look perfect in an external viewer!
    BufferedImage image = ImageIO.read (new File(args[0]));
    ImageIO.write (image, "jpg", new File(args[1]));
    * when I do the scale transformation but store as PNG instead the image looks perfect in external viewers!
    BufferedImage out = op.filter(image,null);
    ImageIO.write(out, "png", new File(args[1]));
    * viewing the scaled JPEG image with The GIMP produces "more intense" (but still wrong) colors than when viewing with the Windows Image Viewer - I suspect that the JPEG doesn't produce plain RGB values when decompressed (another color space used then sRGB? double instead of int values?)
    * Loading the saved image and display it in a JComponent shows the image fine:
    class ViewComponent extends JComponent
         private Image image;
         protected void paintComponent( Graphics g )
              if ( image != null )
    // image looks okay!
                   g.drawImage( image, 0, 0, this );
         public void setImage( BufferedImage newImage )
              image = newImage;
              if ( image != null )
                   repaint();
    * Note that I've tried several input image formats (PNG, JPEG) and made sure that they were stored as RGB (not CMYK or the like).
    * Someone else already mentioned that the RGB values as read from an JPG image are wrong, but no answer in this thread - might be connected with this problem: http://forum.java.sun.com/thread.jspa?forumID=20&threadID=612542
    * I tried the jdk1.5.0_01 and jdk1.5.0_04 on Windows XP.
    Any suggestions? Is this a bug in the ImageIO jpeg plugin? What am I doing wrong? Better try something like JAI or JIMI? I'd rather not...
    Thanks a lot! Oliver
    p.s. also posted to comp.lang.java.programmers today...

    Try using TYPE_NEAREST_NEIGHBOR
    rather than
    TYPE_BILINEARI was a bit quick with saying that this doesn't work - I had extended my example code which made it fail (see later), but here's a working version first (note: I use the identity transform only for simplicity and to show that it really doesn't matter whether I scale, rotate or shear)):
    // works, but only for TYPE_NEAREST_NEIGHBOR interpolation
    Image image = ImageIO.read (new File(args[0]));
    AffineTransform xform = new AffineTransform();
    AffineTransformOp op = new AffineTransformOp (xform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    BufferedImage out = op.filter(image, null);
    ImageIO.write(out, "jpg", new File(args[1]));The problem: we restrict ourselves to nearest neighbor interpolation, which is especially visible when scaling up (or rotate, shear).
    Now when I change the following, it doesn't work anymore, the stored image has type=0 instead of 5 then (which obviously doens't work with external viewers):
    // doesn't work, since an extra alpha value is introduced, even
    // for TYPE_NEAREST_NEIGHBOR
    BufferedImage out = op.filter(image, op.createCompatibleDestImage(image, ColorModel.getRGBdefault()));Intuitively I would say that's exactly what I want, and RGB image with data type int (according to JavaDocs). That it has an alpha channel is a plus - or is it?
    I think this extra alpha value is the root of all evil: JPEG doesn't support alpha, but I guess ImageIO still mixes this alpha value somehow into the JPEG data stream - for ImageIO that's not a problem, the JPEG data is decompressed correctly (even though the alpha values have become meaningless then, haven't checked that), but other JPEG viewers can't manage this ARGB format.
    This also explains why writing to PNG worked, since PNG supports alpha channels.
    And obviously an AffineTransformOp silently changes the image format from RGB to ARGB, but only for TYPE_BILINEAR and TYPE_CUBIC, not for TYPE_NEAREST_NEIGHBOR! Even though I can imagine why this is done like this (it's more efficient to calculate with 32 bit ints than with 24 bit packed values, hence the extra alpha byte...) I would at least expect the JPEG writer to ignore this extra alpha value - at least with the default settings and unless otherwise told with extra parameters! Now my code gets unnecessary complicated.
    So how do I scale an image using bilinear (or even bicubic) interpolation, so that it get's displayed properly with external viewers? I found the following code working:
    // works, but I need an extra buffer and draw operation - UGLY
    // and UNNECESSARILY COMPLICATED (in my view)
    BufferedImage image = ImageIO.read (new File(args[0]));
    AffineTransform xform = new AffineTransform();
    AffineTransformOp op = new AffineTransformOp (xform, AffineTransformOp.TYPE_BILINEAR);
    BufferedImage out = op.filter(image, null);
    // create yet another buffer with the proper RGB pixel structure
    // (no alpha), draw transformed image 'out' into this buffer 'out2'          
    BufferedImage out2 = new BufferedImage (out.getWidth(), out.getHeight(),
                                                             BufferedImage.TYPE_INT_RGB);
    Graphics2D g = out2.createGraphics();
    g.drawRenderedImage(out, null);
    ImageIO.write(out2, "jpg", args[1]);This is already way more complicated than the initial code - left alone that I need to create an extra image buffer, just to get rid of the alpha channel and do an extra drawing.
    I've also tried to supply a BufferedImage as 2nd argument to the filter op to avoid the above:
    ICC_ColorSpace (iccColorSpace = new ICC_ColorSpace (ICC_Profile.getInstance(ColorSpace.CS_sRGB)
    BufferedImage out = op.filter(image, op.createCompatibleDestImage(image, new DirectColorModel (iccColorSpace), 24, 0xff0000, 0x00ff00, 0x0000ff, 0x000000, false, DataBuffer.TYPE_INT)));  But then the filter operation failed ("Unable to transform src image") and I was beaten by the sheer possibilities of color spaces, ICC profiles, so I quickly gave up... and hey, I "just" want to load, scale and save to JPG!
    The last option was getting a JPEG writer and its ImageWriteParam, trying to set the output image type:
    iwparam.setDestinationType(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB));But again I failed, the resulting image type was still type=0 (and not 5). So I gave up, realising that the Java API is still overly complex and "too design-patterned" for simple tasks :(
    If anyone has still a good idea how to get rid of the alpha channel when writing to JPEG in a simple way (apart from creating an extra buffer as above, which works for me now...)... you're very welcome to enlighten me ;)
    Cheers, Oliver
    p.s. Jim, I will assign you the "DukeDollars", since your hint was somewhat correct :)

  • Problem with ImageIO.read and ImageReader JPG colors are distorted/wrong

    (Using JDK 1.5)
    ImageIO incorrectly reads some jpg images.
    I have a jpg image that, when read by the ImageIO api, all the colors become reddish.
            try
                java.awt.image.BufferedImage bi = javax.imageio.ImageIO.read( new java.io.File("javabug.jpg") );
                javax.imageio.ImageIO.write( bi, "jpg", new java.io.File("badcolors.jpg") );
                javax.imageio.ImageIO.write( bi, "png", new java.io.File("badcolors.png") );
            catch ( java.io.IOException ioe )
                ioe.printStackTrace();
            }Why is this happening??? My guess is there is a problem with the ImageIO.read ?
    the jpg can be downloaded at http://www.alwaysvip.com/javabug.jpg
    <BufferedImage@11faace: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@1ebbfde transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 1691 height = 1269 #numDataElements 3 dataOff[0] = 2>
    I have even tried creating a new buffered image but still have the same problem:
    (suggested by http://forum.java.sun.com/thread.jspa?forumID=20&threadID=665585) "Java Forums - ImageIO: scaling and then saving to JPEG yields wrong colors"
            try
                java.awt.image.BufferedImage bi = javax.imageio.ImageIO.read( new java.io.File("javabug.jpg") );
                java.awt.image.BufferedImage out = new java.awt.image.BufferedImage( bi.getWidth(), bi.getHeight(), java.awt.image.BufferedImage.TYPE_INT_RGB );
                java.awt.Graphics2D g = out.createGraphics();
                g.drawRenderedImage(bi, null);
                g.dispose();
                javax.imageio.ImageIO.write( out, "jpg", new java.io.File("badcolors.jpg") );
            catch ( java.io.IOException ioe )
                ioe.printStackTrace();
            }I have used the following which works but does not use the ImageIO api. However, I tried using the ImageIO to write and it worked for writing which leads me to believe there is a problem with the reader.
    (suggested by http://developers.sun.com/solaris/tech_topics/java/articles/awt.html "Server-Side AWT")
            try
                java.awt.Image image = new javax.swing.ImageIcon(java.awt.Toolkit.getDefaultToolkit().getImage("javabug.jpg")).getImage();
                java.awt.image.BufferedImage bufferedImage = new java.awt.image.BufferedImage( image.getWidth( null ), image.getHeight( null ), java.awt.image.BufferedImage.TYPE_INT_RGB );
                java.awt.Graphics g = bufferedImage.createGraphics();
                g.setColor( java.awt.Color.white );
                g.fillRect( 0, 0, image.getWidth( null ), image.getHeight( null ) );
                g.drawImage( image, 0, 0, null );
                g.dispose();
                com.sun.image.codec.jpeg.JPEGImageEncoder encoder = com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder( new java.io.FileOutputStream( "goodcolors.jpg" ) );
                encoder.encode( bufferedImage );
                javax.imageio.ImageIO.write( bufferedImage, "jpg", new java.io.File("goodiocolors.jpg") );
                javax.imageio.ImageIO.write( bufferedImage, "png", new java.io.File("goodiocolors.png") );
            catch ( java.io.IOException ioe )
                ioe.printStackTrace();
            }BTW, the following does not work either:
                java.util.Iterator readers = javax.imageio.ImageIO.getImageReadersByFormatName( "jpg" );
                javax.imageio.ImageReader reader = ( javax.imageio.ImageReader ) readers.next();
                javax.imageio.stream.ImageInputStream iis = javax.imageio.ImageIO.createImageInputStream( new java.io.File("javabug.jpg") );
                reader.setInput( iis, true );
                java.awt.image.BufferedImage bufferedImage = reader.read( 0 );

    I figured out the problem. It was an actual BUG in the JDK!
    The code failed with the following JDKs:
    java version "1.5.0_01"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_01-b08)
    Java HotSpot(TM) Client VM (build 1.5.0_01-b08, mixed mode, sharing)
    java version "1.5.0_03"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_03-b07)
    Java HotSpot(TM) Client VM (build 1.5.0_03-b07, mixed mode)
    The code ran sucessful with this JDK:
    java version "1.5.0_06"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05)
    Java HotSpot(TM) Client VM (build 1.5.0_06-b05, mixed mode, sharing)
    If you are using the ImageIO classes, I highly suggest you upgrade to the latest JDK.
    Best,
    Scott

  • Need help: BufferedImage and zooming

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

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

  • How to output BufferedImage as PNG in HTML page

    I have a servlet that creates a chart as a BufferedImage.
    I can output it as a file using ImageIO.write(bimg,"PNG","fn.ext")
    I would rather put it in a web page but I don't know how.
    It seems I can either put out an html page or an image file
    but not both. Does anyone know how ?

    This question came up in the JFreeChart forum. You can take a look at:
    http://www.object-refinery.com/phorum-3.3.2a/read.php?f=2&i=1598&t=1383
    Hope this helps,
    Dave Gilbert
    www.object-refinery.com

  • Why can't PS CC read .gif and .png files anymore?

    Everytime I've tried to load my files into my PS like usual (simply dragging the photo to the dock) I get this error message "Could not complete your request because Photoshop does not recognize this type of file." for both .gif files and .png. It's quite frustrating because a lot of my files on my computer are in .png format and I have previous .gifs I've made that I'd like to edit and can't. I have a Mac OSX and I've tried rewriting the file names but I still get the same message and I've tried making a new document in PS and pasting the photo but I only end up with the image below. I'm not sure what else to do anymore. It's quite frustrating. Any suggestions?

    All right. That could also explain why my updates aren't working. (I'll try the same for my illustrator because those updates aren't working also.)

  • AE CC crash when drag jpg and png files to comp

    Hi I have noticed photoshop exports of jpg and png files cause AE CC to crash when drag these files  to comp Same jpg and png exported from CS6 do not cause crash.

    What exact version of Photoshop CC are you using? 14.0, 14.1, 14.2?
    How are you saving the PNG and JPEG files from Photoshop? File > Save As? Save for Web?
    In After Effects preferences > Media & Disk Cache, is the Create Layer Markers from Footage XMP Metadata option enabled? Does the problem go away if you turn this off?
    A similar problem recently occurred with files generated from Illustrator CC (17.1):
    http://adobe.ly/1jlIykQ
    However, we have no reason to believe the same problem would apply to files generated from Photoshop. I am not able to reproduce your problem with PNG and JPEG files saved from Photoshop CC (14.2), either from Save As or Save for Web. So either the conditions of your problem are more specific, or it is not related to the XMP Metadata problem.

  • Saving logos as jpg, eps, and png. What mode do I create each in? RGB or CMYK?

    Question... My client has asked for their logo as a JPG, EPS and PNG. They want a file ready to go, so they can fire off logos to whomever for whatever purpose.
    The Pantones are selected. My question, what mode do I create each format (jpg, eps, png) in? CMYK or RGB? Or do I create a CMYK and RGB of each for each format? (The more I know, the less I understand)

    Wow, thanks for your input. I also spoke with a printer with whom I'm working on another job.
    I think I've really over-complicated this, and here's all I really need to send them:
    EPS: Pantone, CMYK, RGB (I have read EPS's are outdated, but she didn't have a problem with it. This way they can take the Pantone colors and try to replicate them as closely as possible)
    JPG: Pantone, CMYK, RGB (per your earlier comments)
    PNG: Pantone, RGB (Web usage)
    PDF/X-4: Printer didn't have strong feelings on this format. She said the EPS would be fine. I'll still send it though.
    Sound good? (I like affirmation)

  • Printing with BufferedImage and Text Quality

    I am using PrinterJob to print text/graphics.
    In my paint method, if we paint directly on the graphics handle using Graphics2D methods, the text quality is very good.
    Our application has to manage a lot of data, and to handle the callabcks for the same page, we are painting to a BufferedImage, and then drawing the BufferedImage unto the graphics handle on the subsequent calls. The overhead to draw the page is significant, and this give us much better performance.
    The PROBLEM IS, the quality of the text using the bufferedImage is like draft quality test, not the high resolution text we get when we paint directly on the supplied handle using the native drawing emthods every time.
    Any idea how we can buffer the page image, and retain the text quality ?
    In the paint we do:
    m_Image = ((Graphics2D)pg).getDeviceConfiguration().createCompatibleImage(m_wPage,m_hPage);
    m_Graphics = (Graphics2D) m_Image.getGraphics();

    Culd u share the fix if u found one

  • Saving jpeg and png files large file size

    Ive recently purchased web premium 5.5 and Im trying to save files in jpeg and png format in Photoshop and Im getting unexpectedly large file sizes, for example I save a simple logo image 246x48 which consists of only 3 basic colours and when I save it as a jpeg quality 11 it reports the file size in the finder as 61.6k, I save it as a png file and its 60.2k also I cropped the image to 190x48 and saved it as a png and the file size is actually larger at 61.9k saving as a jpeg at quality 7 the files size is a still relatively large 54k.
    I have a similar png non indexed colour logo on my mac I saved in CS3 on a pc which is actually larger at 260x148 and it's only 17k and that logo is actually more complex with a gloss effect over part of it. Whats going on and how do I fix it, It's making Photoshop useless especially when saving for the web
    Thanks

    Thanks I had considered that but all my old files are reporting the correct files sizes I have been experimenting and fireworks saves the file at png 24 at 2.6k and jpegs at 5.1k, but I don't really want to have to save the files twice once cut from the comp in photoshop and again in fireworks juggling between the two applications is a bit inconvenient even with just one file but especially when you have potentially hundreds of files to save.
    Ive also turned off icon and windows thumbnail in photoshop preferences and although this has decreased the file size they are still quite large at 27k and save for the web is better at 4k for the png and 16k for the jpeg. Is there anyway to get Fireworks file saving performance in Photoshop ? it seems strange that the compression in Photoshop would be second rate in comparison to fireworks given they are both developed by Adobe and Photoshop is Adobes primary image editing software.

  • Pdf save as jpg and png looks pixelated like it doesn't anti-alias text

    This has been an issue for a while and I can't figure out how to resolve it.  When i open a pdf in acrobat 11.0.0 and click file/save as other/ i can't get the text to anti-alias, it always looks jagged no matter what settings i adjust.
    I can bring the pdf into photoshop or illustrator and can export there but with multiple pages it is a bit absurd.  any ideas?

    thanks bill,
    I'll try to do the updates, it is rather difficult to do when the creative cloud software thinks you are up to date.
    I've tried everything from determine automatically and 72-600 dpi, adjusting the interlace and filter options. It happens regardless of the font - here are 2 more examples on a file created in illustrator, saved off as pdf and then jpg using default settings and png using default settings

  • Just downloaded firefox but it constantly says it needs to update but can't AND PEarl Crescent doesn't work - saved JPEG and PNG files apear as gibberish

    I have installed / de-installed and re-installed firefox on my mac and have had a lot of problems. When I used my PC I always used firefox but it isn't working on my macbook. Firefox is constnantly looking for upgrades but then doesn't actually upgrade and just gets stuck. I downloaded peal crescent (which worked prior to my de-installing and re-installing) and now all PNG and JPG files don't save properly and seem to come out as gibberish (they do hve .jpg and .png at the end)

    You can download Firefox 15.0.1 directly from http://mozilla.com/ and install that directly. Please see this article (and the links in there) for more info: [[How to fix the Update Failed error message when updating Firefox]].
    Are you trying to use [http://pearlcrescent.com/products/pagesaver/ Pearl Crescent Page Saver]? Which feature is not working as designed?

Maybe you are looking for

  • Backing up iPhoto Library from external hard drive through ChronoSync to Time Capsule

    I have a 2008, 2GB Mac Mini.  I moved my iTunes library, which is mostly movies, to a 4 TB My Book Studio, as it exceeded the space on my Mac.  I  back up my computer to a 2 TB Time Capsule.  I exclude the My Book Studio from being backed up on the T

  • CO_TXT_OUTBINDING_ERROR , No standard aggrement found for ,

    Hello, I have a scenario XI-to-IDOC.  I created a Service Interface and publish them as a Web Service. I created a WSDL file from the Integration Builder(Configuration) and When I test the WSDL with the XML Spy, I got a following error message, CO_TX

  • Help with data services webservice in Xcelsius

    Hi, I have the a problem, this is the problem: 1. I add a web service connection, to run a data services job 2. I put thw WSDL URL and after that i click the button import 3. When i click the button IMPORT, that generate a WEB SERVICE URL The problem

  • IPhone content deleting itself & sync issues

    Hi everyone, new here, so hopefully I'll be able to get in everything that needs to be said to help solve the issue. I've got a 64GB iPhone 4S that is completely up-to-date software-wise and has a good 30GB free. All content is added manually from iT

  • About RFCs

    Hi all,         I want to know more about RFCs. What is the diff between transactional async and sync RFCs. Can u tell me vividly so that it can help me in real time.         Also can u send me some good docs on RFCs in my mail id [email protected]