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"));

Similar Messages

  • Corrupted images using ImageIO.read.

    I have looked around and it seems to be a lot of confusion about the point that the corruption occurs. After trying a lot of thing I simplified it to the following code:
    final BufferedImage bimg = ImageIO.read(file);
    JComponent mC = new JComponent() {
    public void paint(Graphics c) {
    c.drawImage(bimg, 0, 0, null, null);
    super.paint(c);
    JFrame ff = new JFrame(file.getName());
    ff.add(mC);
    ff.setVisible(true);
    ff.pack();
    ff.setSize(800, 600);
    ff.validate();Which as I understand means that the corruption happens at read time.
    #Image formats:gif,jpeg
    #Result:
    Some read ok
    Some read half ok/half corrupted (top screen ok/bottom corrupted)
    Some read with overlaying corruption (ie. the image layers are out of place)
    #JVM
    1.4.2
    Java 6 (latest as of 8/6/2007)
    #IDE
    RAD (IBM Eclipse)
    Thank you

    Consider this closed for now. Big portion of my data was corrupted on load time.
    Cheers

  • Using imageio to convert .gif to .jpg gives bad image

    Hi,
    I'm looking at the 1.4 javax.imageio API, and wrote a naive
    program to convert images from one format to another.
    It will read .gif, .jpg or .png and correctly write .gif and .png
    images, but when I try to write a .jpg from a .gif or .png
    the result is very black-looking - actually most of the colour
    is there but changed to a very dark level and red switched to blue
    for example. Presumably there is a reason that this doesn't work,
    or is it a bug? I would've though an exception would be thrown
    if the image types selected were incompatible.
    Also, how does one specify the JPEG quality setting?
    Thanks for any clues,
    Ed
    import javax.imageio.*;
    import java.awt.*;
    import java.io.*;
    import java.awt.image.*;
    public class ImageTest
    public static void main(String[] argv)
    try
    File f1 = new File(argv[0]);
    BufferedImage bi = ImageIO.read(f1);
    System.out.println("Read "+f1+" OK.");
    System.out.println("Image="+bi);
    File f2 = new File(argv[1]);
    String extn = f2.getName();
    extn = extn.substring(extn.lastIndexOf('.')+1);
    ImageIO.write(bi, extn, f2);
    System.out.println("Wrote "+f2+" OK format="+extn);
    catch (Exception ex)
    ex.printStackTrace();

    Interesting, the program works correctly on Windows 2000
    and Solaris Sparc; The .jpg file creating problem only
    occurs on my Solaris x86 machine.
    Ed

  • How to resize image using java imageio

    Hello ,
    I want to know how to resize image using java imageio.
    I dont want to use java awt because i am writing a web application.
    help is very much needed
    thank you.

    Just use an AffineTransform !
    Its much easier

  • How do I convert images to whatever icon MAc uses?

    Client: Mac OS 10.6.6
    Hi All,
    I am coming from the Linux side. In Linux, if I an find an Image I like, I can use it on my desktop Icons. Format is not an issue.
    Questions:
    1) in Mac, I have found it wants a particular format. How do I convert Images (jpeg, png, bitmap, tiff, etc.) to that format?
    2) once I have the image in place, do I need to keep the image around or is it copied into the icon's hidden (in Finder) application directory?
    Many thanks,
    -T

    For anybody using MacPorts, there is a port called makeicns that creates the needed .icns files from the command line.  Usage is pretty simple (from the command):
    makeicns v1.4.10 (284bd686824f)
    Usage: makeicns [k1=v1] [k2=v2] ...
    Keys and values include:
        512: Name of input image for 512x512 variant of icon
        256: Name of input image for 256x256 variant of icon
        128: Name of input image for 128x128 variant of icon
         32: Name of input image for 32x32 variant of icon
         16: Name of input image for 16x16 variant of icon
         in: Name of input image for all variants not having an explicit name
        out: Name of output file, defaults to first nonempty input name,
             but with icns extension
      align: [center, left, right, top, bottom] {First letter suffices!}
    Examples:
      makeicns -512 image.png -32 image.png
          Creates image.icns with only a 512x512 and a 32x32 variant.
      makeicns -in myfile.jpg -32 otherfile.png -out outfile.icns
          Creates outfile.icns with sizes 512, 256, 128, and 16 containing data
          from myfile.jpg and with size 32 containing data from otherfile.png.

  • Converting documents to images using OpenOffice API

    Is it possible to convert e.g. a Word document into a TIFF image using the OpenOffice API with JAI? If so, any pointers as to how this would be done?
    Thanks,
    Harri

    Oops... I didn't notice that you mentioned all that Microsoft stuff. The answer is still yes, I think, but you might want to look into some other language than Java.

  • 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"));
    }

  • 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

  • Converting Image to RenderedImage

    Hi All
    I'm relatively new to Java, and my current problem is as follows:
    I'm trying to convert an Image object to a RenderedImage. If anyone has any clue how to do this, I'd be very greatful for your input!
    Alternatively, does anyone know how to output an Image to a File?
    Thanks!
    Dr Nick

    BufferedImage implements the RenderedImage interface. So what you may want to do is convert your Image to a BufferedImage. They will function the same.
    Use ImageIO in the API:
    static BufferedImage read(ImageInputStream stream)
    Returns a BufferedImage as the result of decoding a supplied ImageInputStream with an ImageReader chosen automatically from among those currently registered. Here's something you may try.
    BufferedImage image = ImageIO.read(file.toURL());You could also do a cast.
    Image i = Toolkit.getDefaultToolkit().getImage("MyImage.jpg");
    BufferedImage bi = new BufferedImage (i.getWidth(this), i.getHeight(this), BufferedImage.TYPE_INT_ARGB);
    bi = (BufferedImage)i;(Note you may skip BufferedImage instantiation on the second line and set the new variable to null)
    You may also get a Graphics object on BufferedImage object and draw the Image object on it:
    g2d.drawImage(i, 0, 0, bi.getWidth(this), bi.getHeight(this), this);
    .Let us know if this works for you.
    Regards,
    Devyn

  • Converting Image to Byte Array and then to String

    Hi All...
    Can anyone please help me. I have got a problem while converting a Byte array of BufferedImage to String.
    This is my code, First i convert a BufferedImage to a byte array using ImageIO.wirte
    public String dirName="C:\\image";
    ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
    BufferedImage img=ImageIO.read(new File(dirName,"red.jpg"));
    ImageIO.write(img, "jpg", baos);
    baos.flush();
    byte[] resultimage=baos.toByteArray();
    baos.close();
    Then i tried to convert this byte array to a string
    String str=new String(resultimage);
    byte[] b=str.getBytes();
    This much worked fine. But when i reversed this process to re-create the image from that string. i found the image distroted.
    BufferedImage imag=ImageIO.read(new ByteArrayInputStream(b));
    ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
    I got this snap.jpg as distroted.
    Please help me i have to convert the image to a string and again i have to re-create the image from that string.

    To conver the bytearray to string use base64.encoding
    String base64String= Base64.encode(baos.toByteArray());
    To convert back use Base64.decode;
    byte[] bytearray = Base64.decode(base64String);
    BufferedImage imag=ImageIO.read(bytearray);

  • Problem in creating 1 image using differnt images

    Dear Fellows I want to create an image by using different images in byte array format. Images may be transparent or normal images. I want final result in byte array. I am using the following technique which is working fine but the problem with this technique is that it takes too much time to create an image. This is because I am using MediaTraker. If I delete the code of MediaTracker then program have undeterministic behavior i.e, sometimes it create the final image properly and sometimes nothing is displayed in final image.
    I need some help from you. If anyone of you know the technique to draw image using different images without using mediaTracker kindly let me know.
    Early replies will be appreciated
    // here is the sample code which i m using for creating image
    byte[] backgroundImage= // read 800 X 600 image from disk and convert it in to byte array
    byte[] image1 = // read 200 X 200 image from disk and convert it in to byte array
    byte[] transparentImage // read 300 X 300 transparent image from disk and convert it in to byte array
    Image img=null;
    Frame frame =new Frame();
    frame.addNotify();
    //creating BufferedImage object to store Final image
    BufferedImage requiredImage= new BufferedImage(800,600,BufferedImage.SCALE_SMOOTH);
    //get Graphics of BufferedImage created above
    Graphics2D g=(Graphics2D) requiredImage.getGraphics();
    ///// begin draw back ground image
    img=Toolkit.getDefaultToolkit().createImage(backgroundImage);
    try
    MediaTracker mt = new MediaTracker(frame);
    mt.addImage(img, 0); // adds image with ID 0
    mt.waitForID(0);
    }catch(Exception myex)
    myex.printStackTrace();
    //draw background starting from x=0, y=0 with 800 X 600 dimentions
    g.drawImage(img,0,0,800,600,null);
    ////////// end draw background image
    ////////// begin draw image1
    img=Toolkit.getDefaultToolkit().createImage(image1);
    try
    MediaTracker mt = new MediaTracker(frame);
    mt.addImage(img, 0); // adds image with ID 0
    mt.waitForID(0);
    }catch(Exception myex)
    myex.printStackTrace();
    //draw image1 starting from x=10, y=10 with 200 X 200 dimentions
    g.drawImage(img,10,10,200,200,null);
    //////////// end draw image1
    //////begin transparentImage
    img=Toolkit.getDefaultToolkit().createImage(backData);
    try
    MediaTracker mt = new MediaTracker(frame);
    mt.addImage(img, 0); // adds image with ID 0
    mt.waitForID(0);
    }catch(Exception myex)
    myex.printStackTrace();
    //draw transparentImage starting from x=400, y=0 with 300 X 300 dimentions
    g.drawImage(img,400,0,300,300,null);
    ///end draw transparent image
    byte []finalResult = //convert requiredImage into byte array;
    you can mail me the solution on my email address [email protected]
    thanks with best regards
    and waiting for someone to reply
    kamran zameer

    is there anyone on this forum to help me??????
    regards,
    kamran zameer

  • Can an Oracle VM be converted for use in VMWare or VirtualBox?

    Does anyone know how to convert / export an Oracle VM for use in VMware Server or in VirtualBox? I've successfully converted VMware images to OVM and VirtualBox images to OVM, but I've not been able to figure out how to get an Oracle VM to convert for use in VMWare or in VirtualBox.
    -Dan
    Edited by: user723595 on Apr 16, 2010 4:10 PM

    The ovs-agent will recognize any strorage device on your VM server which:
    a) is unused and free of any partition, so basically a blank drive
    b) the drive must be recognized by the multipath daemon, so it must be present under /dev/mapper
    So basically, you can't throw in a big drive, partition it, install OVM on it and hope to use the remaining space for your storage pool, you will need the system to recognize at least two independent drives - how ever you going to achieve that is up to you, but the most easy way is to have indeed at least two separate drives installed.

  • I have just bought a hdmi tv and would like to view very high quality images, using apple tv, stored on my external hard drive. I also have blue ray movies stored on my external hd. will i be able to stream these to my tv and view them in 1080p?

    I have just bought a hdmi tv and would like to view very high quality images, using apple tv, stored on my external hard drive. I also have blue ray movies stored on my external hd. will i be able to stream these to my tv and view them in 1080p?

    sorry, why isn't correct?
    i try convert video with quick time to apple tv, import in itunes( that's ok)  but is impossible to synchronize my apple tv ( unsupported file).
    where I wrong?
    please could you explain me the correct procedure?
    i have some video ( holiday movie an photo movie in mpeg2 full HD) to convert for apple tv, and from 2 years some video editing with imovie.
    normally I prepare my video with Imovie, create a file .mov full hd (like master)  and with roxio convert file for apple TV.
    apple world is new for me, after 25 years with microsoft!
    thank so much
    mauro

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

  • Convert photos using the Tools Photoshop Imagine Processor (Photoshop CS 5)

    All of a sudden, I am having issues when I attempt to convert photos using the Tools > Photoshop > Image Processor option in Adobe Bridge.  I used this methodology in the past and the conversion to JPG or TIFFs would fly with no interruption.  Now I am getting now getting getting dialog boxes with "New Snapshot" in the title,  I click OK, then get a message, "The command "Feather" is not currently available," I click "continue, and gert a "New Layer" dialog box, I click OK, and  get a "Fill" dialog box, I click OK and the JPG or Tiff is then generated.  This series then starts over on the next photo to generate.  I am using Photoshop CS5 on a MAC.  I did uninstall and re-install Photoshop l, but I am getting the same series on messages.  Any suggestions?  Thanks

    It sounds like you have an action running when processing the photos
    Look at the bottom of the image processor dialog and and see if Run Action is checked

Maybe you are looking for