Convert Image to BufferedImage

how do i convert an Image object
i) To a BufferedImage object
2) To a RenderedImage object

I tested the following code for copying a tif image onto clipboard and then pasting it on MSWord. It works fine, I have not tried the other way
import java.awt.image.RenderedImage;
import java.io.IOException;
import javax.media.jai.RenderedImageAdapter;
import util.TIFFFileHelper;
public class ClipboardSupport implements ClipboardOwner{
     public ClipboardSupport() {
          super();
     public static void main(String[] args) throws IOException {
          ClipboardSupport co = new ClipboardSupport();
          RenderedImage img=co.getTestImage();
          co.copyToClipBoard(img);
     private RenderedImage getTestImage() throws IOException{
          TIFFFileHelper th = new TIFFFileHelper("C:/workspace/AV/src/images/onepageSample.tif");
          th.getPageCountParseFirstPage();
          RenderedImage img = th.getFirstPage();
          return img;
     public void copyToClipBoard(RenderedImage img2){
          Image img=this.getCovertedImage(img2);
          this.copyToClipBoard(img);
     public void copyToClipBoard(Image img){
          Toolkit tkt = Toolkit.getDefaultToolkit();
          Clipboard clipboard = tkt.getSystemClipboard();
          Transferable t = new ImageSelection(img);
          clipboard.setContents(t,this);
     public void lostOwnership(Clipboard clipboard, Transferable contents) {
          System.out.println("ClipboardSupport.lostOwnership() called");
     private Image getCovertedImage(RenderedImage img) {
          RenderedImageAdapter aid = new RenderedImageAdapter(img);
          Image im = aid.getAsBufferedImage();
          return im;
package util.clipboard;
import java.awt.Image;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
public class ImageSelection implements Transferable {
     private Image img=null;
     DataFlavor dataFlavor = DataFlavor.imageFlavor;
     public ImageSelection(Image img) {
          super();
          this.img=img;
     public DataFlavor[] getTransferDataFlavors() {          
          DataFlavor[] data = new DataFlavor[1];
          data[0]=dataFlavor;
          return data;
     public boolean isDataFlavorSupported(DataFlavor flavor) {          
          if(dataFlavor.equals(flavor)){
               return true;
          }else{
               return false;
     public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
          return img;
}

Similar Messages

  • How convert Image in BufferedImage?

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

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

  • How can I convert an Image ( or BufferedImage ) to Base64 format ?

    Hi folks...
    How can I convert an Image, or BufferedImage, to the Base64 format ?
    The image that I want to convert, I get from the webCam connected to the computer...
    Anyone can help me ?
    Rodrigo Kerkhoff

    I suggest you read this thread concerning this:
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=477461
    Failing that, Google is your friend.
    Good luck!

  • Converting images using ImageIO

    hello all,
    I am in need of help asap.
    Does anyone know how to convert images from jpg/gif to PNG format using Imageiio? I will be very grateful if u can pass this information on to me. I need to convert the images on a server side and send the png image to a mobile (j2me) client.
    Please respond to this if you have ideas on this.
    cheers
    cp

    quite simple.
    for example, you got abc.gif , want to convert to jpp
    BufferedImage bi = ImageIO.read(new File("abc.gif"));
    ImageIO.write(bi, "jpg", new File("abc.jpg"));

  • HowTO: convert Image- byte[] when don't know image format?

    I have byte[] field in my DB. Images have been stored there.
    Images can be jpg/gif/png.
    My task is to scale them and save back (to another field)
    I have such code:
    I know, that getScaledInstance is bad, but please, don't pay attention. This operation +(massive image resizing will be performed once a year at night)+
    public class ImageResizer {
         private static byte[] resizeImage(byte[] sourceImg, int newWidth){
              byte[] result = null;
              Image resizedImage = null;     //output image
              ImageIcon imageIcon = new ImageIcon(sourceImg);     //source image
              Image imageSource = imageIcon.getImage();
              int imageSourceWidth = imageSource.getWidth(null);
              int imageSourceHeight = imageSource.getHeight(null);
              if(imageSourceWidth > newWidth){
                   float scaleFactor =  newWidth/imageSourceWidth;
                   int newHeight = Math.round(imageSourceHeight*scaleFactor);
                 resizedImage = imageSource.getScaledInstance(newWidth, newHeight,Image.SCALE_SMOOTH);
                 Image temp = new ImageIcon(resizedImage).getImage();// This code ensures that all the pixels in the image are loaded.
                 // Create the buffered image.
                 BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),BufferedImage.TYPE_INT_RGB);
                 /**And what next?*/
              }else{
                   result = sourceImg;
              return result;
         public static byte[] scaleToSmall(byte[] sourceImg){
              return resizeImage(sourceImg, 42);
         public static byte[] scaleToBig(byte[] sourceImg){
              return resizeImage(sourceImg, 150);
         public static byte[] serializeObjectToBytearray(Object o) {
             byte[] array;
             try {
               ByteArrayOutputStream baos = new ByteArrayOutputStream();
               ObjectOutputStream oos = new ObjectOutputStream(baos);
               oos.writeObject(o);
               array = baos.toByteArray();
             catch (IOException ioe) {
               ioe.printStackTrace();
               return null;
             return array;
    }On this forum I've found many solutions, but approximately all of them suppose that I know file format (PixelGrabber, ImageIO, e.t.c). But I don't know it. I know, that it can be jpeg/gif/png.
    What can I do?
    I've found that simple serialization can help me (+public static byte[] serializeObjectToBytearray(Object o)+), but seems like it doesn't work.
    Edited by: Holod on 01.11.2008 10:18

    Here I came up with one possible solution using some more functionality of ImageIO.
    public class ImageResizer {
        private static byte[] resizeImage(byte[] sourceBytes, int newWidth) throws Exception {
            byte[] scaledBytes;
            // ImageIO works with Files or Streams, so convert byte[] to stream
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(sourceBytes);
            // Why not just use ImageIO.read(inputStream)? - Because there would be
            // no way to know the original image format (I am assuming here that
            // you need to write back the image in the same format as the original)
            ImageInputStream imageInputStream = ImageIO.createImageInputStream(byteArrayInputStream);
            // assuming there is at least one ImageReader able to read the image
            ImageReader imageReader = ImageIO.getImageReaders(imageInputStream).next();
            // save image format name so we can write it back in the same format
            String formatName = imageReader.getFormatName();
            imageReader.setInput(imageInputStream);
            BufferedImage sourceImage = imageReader.read(0);
            int imageSourceWidth = sourceImage.getWidth();
            int imageSourceHeight = sourceImage.getHeight();
            if (imageSourceWidth > newWidth) {
                // be careful with integer divisions ( 500 / 1000 = 0!)
                double scaleFactor = (double) newWidth / (double) imageSourceWidth;
                int newHeight = (int) Math.round(imageSourceHeight * scaleFactor);
                System.out.println("newWidth=" + newWidth + ", newHeight=" + newHeight + ", formatName=" + formatName);
                // getScaledInstance provides the best downscaling quality but is
                // orders of magnitude slower than the alternatives
                // since you're saying performance is not issue, I leave it as is
                Image scaledImage = sourceImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
                // Unfortunately we need a RenderedImage to use ImageIO.write.
                // So the next lines convert whatever type of Image was returned
                // by getScaledImage into a BufferedImage.
                // Using TYPE_INT_ARGB so potential alpha channels are preserved
                BufferedImage scaledBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
                Graphics2D g2 = scaledBufferedImage.createGraphics();
                g2.drawImage(scaledImage, 0, 0, null);
                g2.dispose();
                // Now use ImageIO.write to encode the image back into a byte[],
                // using the same image format
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ImageIO.write(scaledBufferedImage, formatName, byteArrayOutputStream);
                scaledBytes = byteArrayOutputStream.toByteArray();
            } else {
                // if not scaling happened, just return the original byte[]
                scaledBytes = sourceBytes;
            return scaledBytes;
        public static void main(String[] args) throws Exception {
            // this is just for my own local testing
            // simulate byte[] input from database
            BufferedImage image = ImageIO.read(new File("input.jpg"));
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "PNG", byteArrayOutputStream);
            byte[] sourceBytes = byteArrayOutputStream.toByteArray();
            byte[] scaledBytes = resizeImage(sourceBytes, 640);
            // write out again to check result
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(scaledBytes);
            image = ImageIO.read(byteArrayInputStream);
            ImageIO.write(image, "PNG", new File("output.jpg"));
    }

  • Image to BufferedImage

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

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

  • Extracting image from bufferedimage based on colors

    Hi everyone,
    i have a rather tricky problem: Is it possible to extract an image from a bufferedimage depending on colors. I have images with a black/dark gray item on a mostly white background and need to extract (sub)images of both ends of that item, which is displayed basically horizontally across the iamge.

    yes you can do this no problem
    convert image to pixels (array)
    traverse the array and look for the desired color (threshold)
    when you find a pixel you like, copy it to the new (sub) image or whatever

  • 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

  • Preserving alpha while converting images to grayscale

    I am trying to convert images into grayscale.
    I use this code
    public static BufferedImage grayScale(BufferedImage im) {
            BufferedImage image = new BufferedImage(im.getWidth(), im.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
            Graphics g = image.getGraphics();
            g.drawImage(im, 0, 0, null);
            g.dispose();
            return image;
        }but transparent parts become black. Is there a simple way to preserve opacity while converting to grayscale.

    Since you want to preserve the alpha channel you'll need to get and set the pixels yourself. And you'll have to use a BufferedImage type that
    supports an alpha channel. TYPE_BYTE_GRAY won't do...
    public static BufferedImage grayScale(BufferedImage im) {
         BufferedImage grayImage = new BufferedImage(im.getWidth(), im.getHeith(), BufferedImage.TYPE_INT_ARGB);
         for(int x = 0; x < im.getWidth(); x++)
              for(int y = 0; y < im.getHeight(); y++){
                   int argb = im.getRGB(x,y);
                   int a = (argb >> 24) & 0xff;
                   int r = (argb >> 16) & 0xff;
                   int g = (argb >>  8) & 0xff;
                   int b = (argb      ) & 0xff;
                   int l= (int) (.299 * r + .587 * g + .114 * b) //luminance
                   grayImage.setRGB(x,y, (a << 24) + (l << 16) + (l << 8) + l);
         return grayImage;
    }

  • Error while converting Image -to- PDF and then to PDF/A

    Hi,
    I'm trying to convert a Image format(JPEG,bmp,tiff) to PDF and then to PDF/A. I could able to convert Image to PDF successfully.
    I'm getting the below error while converting the PDF(that was generated) to PDF/A.
    Caused by: com.adobe.livecycle.output.exception.OutputException: Input Document is a already flat PDF Document
    at com.adobe.printSubmitter.PrintServer.transformPDF(PrintServer.java:307)
    at com.adobe.printSubmitter.service.OutputServiceImpl.transformPDFInTxn(OutputServiceImpl.ja va:518)
    at com.adobe.printSubmitter.service.OutputServiceImpl$4.doInTransaction(OutputServiceImpl.ja va:481)
    ... 106 more
    Error OCCURRED: ALC-DSC-000-000: com.adobe.idp.dsc.DSCException: Internal error.
    Please give me the solution to convert PDF to PDF/A?

    I've just read a footnote in the API documentation which indicates that the transformPDF function cannot be used for this purpose:
    "GS_Enterprise said on Nov 24, 2007 at 12:03 PM :
    Please note that the parameter "inPdfDoc" for transformPDF assumes that the stream content is an XFA-based PDF, and that it's not an XFA-based PDF with a PDF background (also known as "XFA foreground"). In other words, this function does not convert any input PDF to PDF/A, but only those PDFs generated from an XFA template which does not include any static PDF content as a background."

  • How do I change my birthdate that was entered in on my Adobe App.  I want to convert images to pdf

    How do I change my birthdate that was entered in on my Adobe App.  I want to convert images to pdf

    What Adobe app?

  • Converting Images to CMYK for Print Publication

    When in my workflow should I be converting images to CMYK for print publication?
    Currently, I shoot RAW photographs with my DSLR in Adobe RGB, import the images into Photoshop for manipulation and then convert the final, sized image to CMYK before placing it in my Indesign document. Before going to print, I convert my files to PDF using the [PDF/X-1a:2001] preset. I use a calibrated system with a profile set for my monitor.
    Since many of my pictures have shades of green, I'm often disappointed with the conversion to CMYK because I lose saturation and brightness. Am I doing anything wrong? Is there a better way of preserving the quality of colour in my images when going to a commercial printer?

    To see in InDesign what color shifts will occur, use View=>Proof Colors.
    I would also recommend View=>Overprint Preview.
    Yes there are color shifts when converting RGB to CMYK, but those are due to the fact that the gamut of CMYK is significantly less than AdobeRGB or even sRGB. The same color shifts going to CMYK will occur whether you convert the image in Photoshop or in InDesign during PDF export or at the RIP.
    Keeping the color in ICC color managed RGB has the advantage that last minute changes can be made as to what CMYK printing conditions are used, i.e. all CMYK is not the same. Furthermore, if you convert RGB to CMYK early in the workflow, you lose the ability to maintain the color gamut for display of the PDF as well as for printing to high fidelity color devices, i.e., offset or digital (especially inkjet) devices that have extra colorants such as light cyan, light magenta, orange, and/or green to dramatically expand the gamut. Once you lose the gamut in your imagery via conversion to CMYK, you can't go back.
              - Dov

  • How can i convert image into pdf  file

    Hi Friends,
    I want to convert image file(i.e. jpeg,bmp,gif) into pdf file using java apis OR is there any tool which can convert it & which we can integrate into our java application
    Thanks in adva.

    Is there any solution to this case.....?

  • Keep the same name while converting images to PDF

    I am using Automator to convert images to PDF. The new images are in a different folder, but it is asking for an output file name. Can't I tell it to just keep the same name as the old file?

    leaving the exact format, can you explain what does it mean by correctly formed Arabic fonts ?
    What I did is created a text document in Arabic and converted it to PDF and the same file is converted back to word and the results were all junk..

  • How to convert image to binary format

    Hi all,
      We have developed an Employee search  mobile web application in .net which is hosted on an exposed IP server, we need to show the employee data along with the image of the employee on mobile.
    When we run this application through our desktop we are able to see the image of the employee since we are doing this through <b>intranet</b> , but when we try to access the same from any mobile device we are able to see only the data but no image, since we are doing this through <b>internet(exposed server).</b>
    Please suggest some way to get this image,
    is there any<b> function module in ABAP</b> which can <b>convert image to binary format</b>
    so that we <b>export binary data</b> to .net application

    Hei evryone!
    CAn anyone pls help me on how to solve this error:
    java.security.AccessControlException: access denied (java.security.SecurityPermission insertProvider.SunJCE)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkSecurityAccess(Unknown Source)
         at sun.plugin.security.ActivatorSecurityManager.checkSecurityAccess(Unknown Source)
         at java.security.Security.check(Unknown Source)
         at java.security.Security.insertProviderAt(Unknown Source)
         at java.security.Security.addProvider(Unknown Source)
         at CryptoTest.processFile(SwingApplet.java:68)
         at CryptoTest.<init>(SwingApplet.java:65)
         at SwingApplet.init(SwingApplet.java:39)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Is it allright for a swing code to access local resources? like in my case i want my swing app to decrypt and encrypt an image file but when i tried to access the method for decrypting and encrypting i got this error message on my console. Do i have to make my code signed before i could write/read a file on my hard drive?
    Any help / suggestions would be much appreciated.Thanks!

Maybe you are looking for

  • ASA 5505 /VPN/Radius

    Hello Trying to configure VPN access via radius on ASA 5505 Trying to test authentication, but geting an errror see below Thanks aaa-server RADIUS protocol radius aaa-server RADIUS (inside) host x.x.x.x key ***** radius-common-pw ***** aaa-server TAC

  • ViewDocument.jsp gets null pointer exception when using report token instead of docid for DHTML

    <p>The following command gets a null pointer error showing up in Tomcat log:</p><p>../../viewers/cdz_adv/viewDocument.jsp?sEntry=<%=strEntry%>&lang=en&iDocID=830&ViewType=I&kind=Webi</p><p>where sEntry is a valid report token </p><p>but works fine if

  • Wireless Network Does Not Always Connect Successfully on HP ENVY 5644

    Just purchased a new HP ENVY 5644 device to replace an existing my HP Photosmart C4380. Powered the new device on for the first time and ran through the initial setup using the integrated touchscreen. Everything seemed to go both easily and smoothly,

  • XSLT mapper: How to deal with $ character

    Hi, I am facing problem with my transformation. I am trying to map my source database(AS400) to the destination database(Oracle) by using DB Adapter. My source table column name contains $ signs like P$id,P$name. Now when I am trying to open the mapp

  • Playlist order not updating!

    I have been using my iPod Shuffle for several months to listen to podcasts, among other things. I know how to drag files in the playlist so I know what will play first. For some reason now, the playlist shown in iTunes (6.01) is NOT reflected on my i