Writing JPEG with ImageIO

Hi,
I wanted to do this little tool that:
1. read any type of image format supported by ImageIO
2. scaled it down to arbitrary size
3. wrote the image to the same format it was originally
I got the pieces together, used ImageIO to read the image, then java.awt.image.AffineTransformOp to scale it down and finally ImageIO again to write it back (I get the ImageWriter with ImageIO.getImageWriter(ImageReader)).
The problem I got was that AffineTransformOp on Linux (it uses native code) does not want to output anything else then ARGB images. If I read a YCbCr JPEG (the most common JPEG format) and do the AffineTransformOp, I get this ARGB image, which ImageIO will happily write back as an JPEG, but as CMYK JPEG file (which is really rare and not understood by most browsers)... which is not fine because the original was YCbCr.
The question now is, how do I get AffineTransformOp and ImageIO to play nicely together. Either I have to get AffineTransformOp to output to an BufferedImage that has the same colormodel as that read from the file, or I have to get ImageIO to write any BufferedImage to the exact same format as the original image file.
For the special case I stated above, I got the program to work by converting the BufferedImage I got from AffineTransformOp to a BufferedImage with RGB colormodel. This, however is not the solution because it assumes that we do not want to output ARGB... Anyway I did it whith the following code (yes, it is horrible).
// do scaling
BufferedImage scaled = op.filter(original, null);
// create a new RGB color model... no alpha
ColorModel rgbcm = new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 0x000000ff);
// get the DataBuffer from the scaled version
DataBuffer db = scaled.getRaster().getDataBuffer();
// and its dimensions
int w = scaled.getRaster().getWidth();
int h = scaled.getRaster().getHeight();
// band masks for rgb (no alpha)
int[] bandMasks = new int[] {0x00ff0000,0x0000ff00, 0x000000ff}
// create new WritableRaster that has the same data, but different sample model
WritableRaster r = Raster.createPackedRaster(db, w, h, h, bandMasks, null);
// create a new BufferedImage with the no-alpha ColorModel and the raster
// with no-alpha SampleModel
BufferedImage rgbimg = new BufferedImage(rgbcm,r, scaled.isAlphaPremultiplied(), null);
My second question is, if I have to do this, is there any simpler way?

I just did a project similar to this actually, so you're in luck! My project was doing image compression rather than resizing, but the IO is the same. I used PixelGrabber to get the pixels, then created my new image in a BufferedImage just like you did (so you can keep all your reading and image creation the same since you seemed to use a BufferedImage also).
Once you have your BufferedImage, it's blazingly simple. There is a JPEGCodec package that is included in the JDK. It's not compiled though. but, if you open up the ZIP file that has the sources in it (it's copied to your java home directory, called "src.zip"), you can get all the sources you needed. In that package there are 2 classes that I used: JPEGCodec and JPEGImageEncoder. It works like follows:BufferedImage bi;
OutputStream os;
// create and fill your buffered image and instantiate your output stream (I used a FileOutputStream for obvious reasons).
JPEGImageEncoder jie = JPEGCodec.createJPEGEncoder(os);
jie.encode(bi); And that's it! The package does the rest! Let me know if you have any troubles with it.

Similar Messages

  • Reading TIFF, Writing JPEG with Advanced Imaging

    I am working on a servlet that will read a TIFF image file from a SOCKET connection, and write it to a JPEG file for viewing by the user. I've been able to read the TIFF file into a byte array, but I'm not sure how to write it back out as a JPEG. The code snippet below is being used to read the TIFF from the SOCKET:
    for (int i=0; i < imageCount; i++)
    imageSocket = new Socket("imageServer", 4178);
    toImage = new PrintWriter(imageSocket.getOutputStream(), true);
    fromImage = new BufferedReader(new InputStreamReader(imageSocket.getInputStream()));
    toImage.println(imageNames);
    int fileSize = Integer.parseInt(fromImage.readLine());
    if (fileSize > 0)
    byte[] image = new byte[fileSize];
    for (int j=0; j < fileSize; j++)
    image[j] = (byte) fromImage.read();                
    else
    System.out.println("file size is zero"); /* display msg for now */
    I'd prefer to do this using the Advanced Imaging API,s but can't find a decent example to look at. Can anyone help me find a better way of doing this?
    Thanks!

    You will get some help from following guide.
    http://java.sun.com/products/java-media/jai/forDevelopers/jai1_0_1guide-unc/index.html

  • How to read and write Png and jpeg with  Alpha

    Hi
    I have trouble reading and writeing PNG and JPEGs that have an alpha channel (for transparency).
    Reading works, if i use Toolkit.getImage() method, but works NOT if i use ImageIO.read() method.
    Writing does NOT work using ImageIO.write()method. Instead i got a "java.lang.UnsupportedOperationException: Unsupported write variant!"
    See Test class and commandline output below:
    /****************START*****************************/
    package de.multivisual.bodo.test;
    import java.awt.*;
    import java.awt.image.*;
    import java.io.File;
    import java.net.URL;
    import java.util.Iterator;
    import javax.imageio.*;
    import javax.imageio.metadata.IIOMetadata;
    import javax.imageio.stream.ImageInputStream;
    import javax.imageio.stream.ImageOutputStream;
    public class AlphaChannelTest implements ImageObserver {
      Toolkit toolkit;
      Image img;
      public AlphaChannelTest() {
        super();
        toolkit = Toolkit.getDefaultToolkit();
        URL url =
          AlphaChannelTest.class.getResource(
            "/de/multivisual/bodo/test/" + "alphatest.png");
        img = toolkit.getImage(url);
        try {
          ImageInputStream imageInput =
            ImageIO.createImageInputStream(url.openStream());
          Iterator it = ImageIO.getImageReaders(imageInput);
          ImageReader reader = null;
          while (it.hasNext()) {
            reader = (ImageReader) it.next();
            System.out.println(reader.toString());
          reader.setInput(imageInput);
          ImageReadParam param = reader.getDefaultReadParam();
          BufferedImage bimg = reader.read(0, param);
          SampleModel samMod = bimg.getSampleModel();
          ColorModel colMod =       bimg.getColorModel();
          String[] propNames = bimg.getPropertyNames();
          IIOMetadata meta = reader.getImageMetadata(0);
          System.err.println("\n*****test image that was read using new Jdk 1.4 ImageIO.read() method");
          alphaTest(bimg);
        } catch (Exception e) {
          //e.printStackTrace();
        if (img != null)
          toolkit.prepareImage(img, -1, -1, this);
        try {
          synchronized (this) {
            System.out.println("wait");
            this.wait();
        } catch (Exception e) {
          e.printStackTrace();
        System.out.println("end");
      public void alphaTest(BufferedImage bi) {
        Raster raster = bi.getData();
        float[] sample = null;
        System.out.println("raster :");
        for (int y = 0; y < raster.getHeight(); y++) {
          for (int x = 0; x < raster.getWidth(); x++) {
            sample = raster.getPixel(x, y, sample);
            System.out.print("(");
            for (int i = 0; i < sample.length; i++) {
              System.out.print(":" + sample);
    System.out.print(")");
    System.out.println();
    Raster araster = bi.getAlphaRaster();
    if (araster == null){
         System.err.println("there is no Alpha channel!!!!!!!!!");
         return ;
    } else {
         System.out.println("Alpha channel found !");
    float[] asample = null;
    System.out.println("raster alpha:");
    for (int y = 0; y < araster.getHeight(); y++) {
    for (int x = 0; x < araster.getWidth(); x++) {
    asample = araster.getPixel(x, y, asample);
    for (int i = 0; i < asample.length; i++) {
    System.out.print(" " + asample[i]);
    System.out.println();
    String format ="PNG";
    System.out.println("##########Test Writing using new JDK1.4.1 ImageIO:");
    Iterator writers = ImageIO.getImageWritersByFormatName(format);
    ImageWriter writer = (ImageWriter) writers.next();
    ImageWriteParam param = writer.getDefaultWriteParam();
    ImageTypeSpecifier imTy = param.getDestinationType();
    ImageTypeSpecifier imTySp =
    ImageTypeSpecifier.createFromRenderedImage(bi);
    param.setDestinationType(imTySp);
    File f = new File("c:/tmp/myimage."+format);
    try {
    ImageOutputStream ios = ImageIO.createImageOutputStream(f);
    writer.setOutput(ios);
    writer.writeInsert(0, new IIOImage(bi, null, null), param);
    } catch (Exception e) {
         System.err.println("could not write "+format+" file with alpha channel !");
    e.printStackTrace();
    public boolean imageUpdate(
    Image img,
    int infoflags,
    int x,
    int y,
    int width,
    int height) {
    if ((toolkit.checkImage(img, -1, -1, null)
    & (ImageObserver.HEIGHT | ImageObserver.WIDTH | ImageObserver.ALLBITS))
    == 35) {
    int iw = img.getWidth(this);
    int ih = img.getHeight(this);
    BufferedImage bi = new BufferedImage(iw, ih, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D big = bi.createGraphics();
    big.drawImage(img, 0, 0, this);
    System.err.println("+++++test image that was read using old Toolkti.getImage method");
    alphaTest(bi);
    synchronized (this) {
    this.notifyAll();
    return false;
    return true; // image is not yet completely loaded into memory
    public static void main(String[] args) {
    //     BufferedImage image = new
    // BufferedImage();
    new AlphaChannelTest();
    /*************************END********************/
    The commandline looks like this:
    [i]
    com.sun.imageio.plugins.png.PNGImageReader@d1fa5
    *****test image that was read using new Jdk 1.4 ImageIO.read() method
    raster :
    there is no Alpha channel!!!!!!!!!
    wait
    +++++test image that was read using old Toolkti.getImage method
    raster :
    Alpha channel found !
    raster alpha:
    ##########Test Writing using new JDK1.4.1 ImageIO:
    could not write PNG file with alpha channel !
    java.lang.UnsupportedOperationException: Unsupported write variant!
         at javax.imageio.ImageWriter.unsupported(ImageWriter.java:600)
         at javax.imageio.ImageWriter.writeInsert(ImageWriter.java:973)
         at de.multivisual.bodo.test.AlphaChannelTest.alphaTest(AlphaChannelTest.java:113)
         at de.multivisual.bodo.test.AlphaChannelTest.imageUpdate(AlphaChannelTest.java:135)
         at sun.awt.image.ImageWatched.newInfo(ImageWatched.java:55)
         at sun.awt.image.ImageRepresentation.imageComplete(ImageRepresentation.java:636)
         at sun.awt.image.ImageDecoder.imageComplete(ImageDecoder.java:135)
         at sun.awt.image.PNGImageDecoder.produceImage(PNGImageDecoder.java:511)
         at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:257)
         at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:168)
         at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
    end

    in between i found out that the my png and jpeg test images did not have an alpha channel, since the tool i used to create them, did not write the alpha channel to disk.
    if i use png with alpha channel, then the read works correktly with ImageIO.read()
    however the read problem still remains for gifs and the write does not work for gifs and neither for pngs.
    whether jpegs can be read with alphachannel i don't know since i don't have a tool to create jpeg with alpha channel. (at least gimp and corel9 are not able to )
    and it is not possible to write the previous read png with alpha channel back as and jpeg with alpha channel

  • Problems with ImageIO.write()

    Well I am finding it very strange with ImageIO.write();
    Consider the following code snippet:
    BufferedImage img=ImageIO.read(new File("fw2.jpg"));
    BufferedImage img1=new BufferedImage(img.getWidth(),img.getHeight(),img.TYPE_INT_ARGB);
    for(int i=0;i<img.getHeight();i++)
    for(int j=0;j<img.getWidth();j++)
    img1.setRGB(j,i,img.getRGB(j,i));
    ImageIO.write(img1,"jpg",new File("fwinv.jpg"));
    So simply I am copying fw2.jpg to fwinv.jpg. fw2.jpg was also created
    using ImageIO.write().
    But the two files are having different pixel values.
    i.e If I read fwinv.jpg again I will get different pixel value that it was written.
    Why is this...Can any one please help me..

    Reading the written images back and displaying them in java works okay. The third image looks okay in RGB but wrong in ARGB when displayed by a native app. For more about this see reply 1 in Color problems and the linked bug report: Some Images written using JPEG Image Writer are not recognized by native applns.
    import java.awt.GridLayout;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class WriteTest {
        private JPanel getContent(BufferedImage src) throws IOException {
            File fileOne = new File("fileOne.jpg");
            ImageIO.write(src, "jpg", fileOne);
            BufferedImage image1 = ImageIO.read(fileOne);
            BufferedImage image2 = copy(image1);
            JPanel panel = new JPanel(new GridLayout(1,0));
            panel.add(new JLabel(new ImageIcon(src)));
            panel.add(new JLabel(new ImageIcon(image1)));
            panel.add(new JLabel(new ImageIcon(image2)));
            return panel;
        private BufferedImage copy(BufferedImage in) throws IOException {
            int w = in.getWidth();
            int h = in.getHeight();
            int type = BufferedImage.TYPE_INT_ARGB;   // problem in native apps
                       //BufferedImage.TYPE_INT_RGB;  // this one works okay
            BufferedImage out = new BufferedImage(w, h, type);
            for(int y = 0; y < h; y++) {
                for(int x = 0; x < w; x++) {
                    out.setRGB(x, y, in.getRGB(x, y));
            File fileTwo = new File("fileTwo.jpg");
            ImageIO.write(out, "jpg", fileTwo);
            return ImageIO.read(fileTwo);
        public static void main(String[] args) throws IOException {
            BufferedImage image = ImageIO.read(new File("images/cougar.jpg"));
            WriteTest test = new WriteTest();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test.getContent(image));
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }

  • "Save image" button of Camera Raw does not save JPEG with modifications made.

    I am using Bridge CC to process my RAW images and make modifications to some JPEG images as well.  I have no need to further alter images in Photoshop at the moment, so I do all modifications in Camera Raw. After altering my images, I then press the "save image" button at the left bottom corner of Camera Raw and choose the settings to save in JPEG.  However, when I upload these JPEG images to a website or when I email them, the image is uploaded without the modifications I had done!  It seems to me that Camera Raw is saving JPEGs the same way it does for RAW images, in a non-destructive manner, only attaching instructions for the images to be displayed properly on Photoshop. But when I save an image in JPEG, I expect the image to be saved entirely with the modifications I made while still keeping the original RAW file.  What goes on then?  What is Camera Raw doing and how do I get to save a modified image in JPEG with Camera Raw?  Would you please explain?
    Many thanks for your help,
    Beza

    Hi,
    What version of camera raw and operating system are you using?

  • Problem with Arabic font: In certain contexts, when writing Arabic with vowel signs (fatha, damma, kasra, sukun) a sequence of sukun   fatha/damma etc. would reverse automatically. Is this a known bug?

    Problem with Arabic font: In certain contexts, when writing Arabic with vowel signs (fatha, damma, kasra, sukun) a sequence of sukun + fatha/damma etc. would reverse automatically. Is this a known bug?
    Example: عَيْنٌ
    would automatically convert to عَيُنْ
    Funnily, it doesn't seem to happen here, but it does when entering text in a web interface (using Firefox, font Bayan) and when using Text Edit.
    Seems to be a problem of a specific font, as e.g. Arial MS Unicode works fine. Any hints?
    Thank you!

    Musaafir wrote:
    I've no idea how i can even start using arabic vowels on Microsoft Word for Apple
    You can't do Arabic on MS Word for Mac.  This app has never supported RTL scripts, so you need to use something else.  Mellel is best, but Pages 5, TextEdit, Nisus Writer, Open/LibreOffice should work OK.
    You switch between languages by using the "flag" menu at the top right of the screen or by using the keyboard shortcuts apple/command plus space.  Go to system prefs/keyboard/shortcuts to make sure that is activated.
    To see which key does what, you use Keyboard  Viewer.
    http://support.apple.com/kb/PH13746
    You place vowels on letters by typing the key for the vowel after the key for the letter.  The vowels are on the option/alt keys, option/alt + a gives you َ

  • Three keys of my keyboard are not working, the cap one, the return key and the space bar, while the virtual keyboard shows to others keys highlighted in orange (^ and `); How to fix it? I writing now with a bluetooth keyboard.

    Three keys of my keyboard are not working, the cap one, the return key and the space bar, while the virtual keyboard shows to others keys highlighted in orange (^ and `); How to fix it? I writing now with a bluetooth keyboard.

    All new keyboards need Snow Leopard 10.6.8 and above for full functionality.
    Rather short-sighted of Apple perhaps, but that seems to be a trend these days.
    I'm afraid the only fix is to upgrade to SL. Personaly, I'd take it back and get a refund and seek an older keyboard or a third-party one elsewhere.

  • Writing files with Eclipse over gvfs ends in empty files

    Hello,
    I'm using gvfs to mount folders from our development server. I'm accessing these folders directly with Eclipse. Everything went fine until the last gnome update. Now writing files with Eclipse ends in writing empty files, but there aren't any errors. Eclipse still shows the content of the files until i reopen them.
    When i'm writing files with other apps (vim, gedit) everything works normally?
    Does anybody have any suggestions?
    Thx

    Hello,
    I'm using gvfs to mount folders from our development server. I'm accessing these folders directly with Eclipse. Everything went fine until the last gnome update. Now writing files with Eclipse ends in writing empty files, but there aren't any errors. Eclipse still shows the content of the files until i reopen them.
    When i'm writing files with other apps (vim, gedit) everything works normally?
    Does anybody have any suggestions?
    Thx

  • Open untagged JPEG with external editor, then be attached with sRGB profile

    Hi there,
    I wonder why I open untagged JPEG with "external editor" (Photoshop CS) , then the JPEG will be attached with sRGB profile. Of course my color setting on photoshop is "Use the embedded profile".
    I think sRGB is the default RGB space of colorsync utility , because the profile is also sRGB when you check "Add Colorsync Profile" on iPhoto 6.
    Anyway , I want to set up total Adobe RGB workflow , so does anybody know how to change sRGB profile to Adobe RGB profile when opening untagged JPEG directly with external editor?

    Thank you for your reply , Lloyd.
    I am sorry , but I noticed my misunderstanding message.
    As you know , you can change raw and other image files to tiff or psd for external editor. You can select that on the preference. At this situation , if you pass nontagged image file to external editor , then automatically sRGB profile is attached.
    I don't think this is related to export preset for JPEG file.

  • How to save JPEGs with a clean matte?

    From a cut-out image on a transparent background, I use Save for web specifying a black matte to create a JPEG. The resulting image has compression artefacts within the black matte around the image just the same as if the original image had a black background. I can then apply a mask channel copied from the orignal file to the JPEG and fill the matte with black. Delete the mask and Save and I have a JPEG with a matte free of artefacts.
    Is there a simple way to achieve the same thing and what's the point of the matte option?

    I am currently using .png files with transparent backgrounds and dropshadows. These are significantly larger (2x or 3x) than the equivalent .jpg files so the site loading time is also much longer but, of course, .jpgs don't allow transparency. My sites are in Flash which, via ActionScript, allows me to apply drop shadows at runtime to transparent images. It also allows me to create a transparent bitmap image from a .jpg by setting to transparent all pixels that have the matte colour. Unfortunately, as I described above, not all the pixels in the matte area will retain the matte colour because of the way the JPEG compression is done. As a result, the cut out image created by ActionScript will not have clean edges. I can fix this by the second operation on the .jpg I've described but this process is not easily automated in an Action and one site in particular involves a lot of images!

  • Exporting jpegs with embedded previews?

    For compatibility with a web application I wrote using an old workflow ending with a save-for-web in Photoshop, I need to export jpegs with embedded previews. (Not DNG or other format files with embedded jpeg previews.) This happens by default with Photoshop, but Lightroom doesn't do it and I can't find anything to change that in the settings. Am I missing something? And if this isn't included, is it on the to-do list for improvements?

    Hi Andrew,
    Please refer to the following forum post : http://forums.adobe.com/message/5770863#5770863
    Regards,
    Aish

  • RAW+JPEG with unsupported RAW

    I'm now using a Panasonic Lumix DMC-L1 (and really liking it), whose RAW files aren't yet supported by Aperture. I figured out that Aperture silently imports the JPEGs with the RAWs (camera shoots RAW+JPEG), and also how to make a version from the JPEG master.
    Is there any way to re-associate a JPEG master with a RAW master inside a project? I accidentally deleted a JPEG master. I could pull it out of the trash and reimport it, but then it was not considered associated with the RAW master. I ended up deleting both masters and reimporting to reconnect the masters.
    The other question is there any way to edit externally the RAW file? Aperture's external editing feature seems to only export as TIFF or PSD, but my camera came with Silkypix which is a very capable (but odd) RAW editor. If I import the RAWs into Aperture I don't see any way to use Silkypix as an editor. Any ideas, or does it just make more sense not to put the RAWs into Aperture as long as I have to use Silkypix? RAW shooting is a new thing for me.
    PowerBook 15" 1.5GHz   Mac OS X (10.4.8)  

    That seems a lot of effort, so can you not edit the
    RAW's before importing to Aperture and then use
    Aperture for image management, fine tuning, selects
    etc.?
    Exactly the course I've decided to take until Aperture supports my camera's RAW. After some photo comparisons I've decided to shoot RAW and ignore the camera's JPEG, develop to 16-bit TIFF with Silkypix and then import the TIFFs into Aperture. It takes a bit of processing time up front, but the quality is worth it.
    I've put together a side-by-side comparison of the camera's JPEG and the JPEG I export from Aperture after going through the RAW-to-TIFF conversion. The quality difference is quite noticeable.
    See the comparison picture at http://www.puppethead.com/misc/lumix_l1-compare.jpg
    PowerBook 15" 1.5GHz   Mac OS X (10.4.8)  

  • I am having an issue writing texts with Siri on iPhone 5 iOS 6.  When I do it just talking to the phone it works fine. However if I speak through the ear pod headphones or Bluetooth headset it only writes about 5 works before trying to send.

    I am having an issue writing texts with Siri on iPhone 5 iOS 6.  When I do it just talking to the phone it works fine. However if I speak through the ear pod headphones or Bluetooth headset it only writes about 5 works before trying to send.
    Does anyone know why this might be?

        Hello APVzW, we absolutely want the best path to resolution. My apologies for multiple attempts of replacing the device. We'd like to verify the order information and see if we can locate the tracking number. Please send a direct message with the order number so we can dive deeper. Here's steps to send a direct message: http://vz.to/1b8XnPy We look forward to hearing from you soon.
    WiltonA_VZW
    VZW Support
    Follow us on twitter @VZWSupport

  • Jpeg encoding with imageio - pink distortion problem

    Hello, I am using the imageio classes to scale down jpg images (for thumbnails) and write them to a file. On most images, everything works perfectly. On some images, however, the resulting thumbnail image has a strange pink coloration to the whole picture. Does anyone have any ideas as to why this would happen? The code I am using is below. I thank anyone that takes the time to read this and hope someone can help.
    import java.awt.Graphics2D;
    import java.awt.geom.AffineTransform;
    import java.awt.image.AffineTransformOp;
    import java.awt.image.BufferedImage;
    import java.awt.image.IndexColorModel;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import javax.imageio.IIOImage;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageTypeSpecifier;
    import javax.imageio.ImageWriteParam;
    import javax.imageio.ImageWriter;
    import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
    import javax.imageio.stream.ImageOutputStream;
    public class ImageResizer
         private static final int THUMBNAIL_MAX = 120;
         private static final int SMALL_MAX = 250;
         private static final int LARGE_MAX = 575;
         private static final int LARGE_THRESHOLD = 425;
         BufferedImage inImage;
         int width;
         int height;
         private static JPEGImageWriteParam params;
         static {
              JPEGImageWriteParam params = new JPEGImageWriteParam(null);
              params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
              params.setCompressionQuality(0.8f);
              params.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
              params.setDestinationType(
                   new ImageTypeSpecifier(IndexColorModel.getRGBdefault(),
                   IndexColorModel.getRGBdefault().createCompatibleSampleModel(16,16)));
         public ImageResizer(byte[] image, long id) throws IOException
              inImage = ImageIO.read(new ByteArrayInputStream(image));
              width = inImage.getWidth(null);
              height = inImage.getHeight(null);
         public void makeSmallImage (File outputFile) throws IOException {
              resizeImage(120, outputFile);
         private void resizeImage (int maxDim, File file) throws IOException {
              double scale = maxDim / (double) height;
              if (width > height) scale = maxDim / (double) width;
              int scaledWidth = (int)(scale * width);
              int scaledHeight = (int)(scale * height);
              BufferedImage outImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
              AffineTransform xform = AffineTransform.getScaleInstance(scale, scale);
              AffineTransformOp op = new AffineTransformOp(xform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
              // Paint image.
              Graphics2D g2d = outImage.createGraphics();
              g2d.drawImage(inImage, op, 0, 0);
              g2d.dispose();
              // write the image out
              ImageOutputStream ios = null;
              try {
                   ios = ImageIO.createImageOutputStream(file);
                   ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByFormatName("jpg").next();
                   writer.setOutput(ios);
                   writer.write(null, new IIOImage(outImage, null, null), params);
                   writer.dispose();
              catch (IOException e) {
                   System.out.println("cought IOException while writing " +
                   file.getPath());
              finally {
                   if (null != ios) ios.close();
    }

    I am having the same problem with jpegs.
    The strange thing is that this only happends with the same exact code on OS X, while it never happens on any windows machine.
    I have tried using the the ImageIO classes, and a class I got off of this board a while back; however when using this class on an OS X machine, encoding takes a really long time and gives the pink distortion.
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.swing.*;
    import com.sun.image.codec.jpeg.*;
    import java.awt.event.*;
    import java.util.*;
    import java.awt.geom.*;
    public class ImageUtils {
         private static JPEGImageEncoder encoder = null;
         private static FileOutputStream fileStream = null;
         public static BufferedImage createComponentImage(Component component)
              BufferedImage image = (BufferedImage)component.createImage(component.getWidth(),component.getHeight());
              Graphics graphics = image.getGraphics();
              if(graphics != null) { component.paintAll(graphics); }
              return image;
         public static void encodeImage(BufferedImage image, File file) throws IOException
              fileStream = new FileOutputStream(file);
              JPEGEncodeParam encodeParam = JPEGCodec.getDefaultJPEGEncodeParam(image);
              encoder = JPEGCodec.createJPEGEncoder(fileStream);
              encoder.encode(image,encodeParam);
    }use it like this:
    File file = new File("ImageTest.jpg");
    image = ImageUtils.createComponentImage(imageCanvas);
    ImageUtils.encodeImage(image,file);

  • ImageIO PNG Writing Slow With Alpha Channel

    I'm writing a project that generates images with alpha channels, which I want to save in PNG format. Currently I'm using javax.ImageIO to do this, using statements such as:
    ImageIO.write(image, "png", file);
    I'm using JDK 1.5.0_06, on Windows XP.
    The problem is that writing PNG files is very slow. It can take 9 or 10 seconds to write a 640x512 pixel image, ending up at around 300kb! I have read endless documentation and forum threads today, some of which detail similar problems. This would be an example:
    [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6215304|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6215304]
    This surely must be resolvable, but after much searching I've yet to find a solution. If it makes any difference, I ONLY want to write png image, and ONLY with an alpha channel (not ever without), in case there are optimisations that that makes possible.
    If anyone can tell me how to address this problem, I'd be very grateful.
    Many thanks, Robert Redwood.

    This isn't a solution, but rather a refinement of the issue.
    Some of the sources I was reading were implying that the long save time might be due to a CPU heavy conversion process that had to take place before the BufferedImage could be saved. I decided to investigate:
    I loaded back in one of the (slowly) saved PNG images using ImageIO.read(file). Sure enough, the BufferedImage returned differed from the BufferedImage I had created. The biggest difference was the color model, which was DirectColorModel on the image I was generating, and was ComponentColorModel on the image I was loading back in.
    So I decided to manually convert the image to be the same as how it seemed to end up anyway. I wrote the following code:
          * Takes a BufferedImage object, and if the color model is DirectColorModel,
          * converts it to be a ComponentColorModel suitable for fast PNG writing. If
          * the color model is any other color model than DirectColorModel, a
          * reference to the original image is simply returned.
          * @param source The source image.
          * @return The converted image.
         public static BufferedImage convertColorModelPNG(BufferedImage source)
              if (!(source.getColorModel() instanceof DirectColorModel))
                   return source;
              ICC_Profile newProfile = ICC_Profile.getInstance(ColorSpace.CS_sRGB);
              ICC_ColorSpace newSpace = new ICC_ColorSpace(newProfile);
              ComponentColorModel newModel = new ComponentColorModel(newSpace, true, false, ComponentColorModel.TRANSLUCENT, DataBuffer.TYPE_BYTE);
              PixelInterleavedSampleModel newSampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, source.getWidth(), source.getHeight(), 4, source.getWidth() * 4, new int[] { 0, 1, 2, 3 });
              DataBufferByte newDataBuffer = new DataBufferByte(source.getWidth() * source.getHeight() * 4);
              ByteInterleavedRaster newRaster = new ByteInterleavedRaster(newSampleModel, newDataBuffer, new Point(0, 0));
              BufferedImage dest = new BufferedImage(newModel, newRaster, false, new Hashtable());
              int[] srcData = ((DataBufferInt)source.getRaster().getDataBuffer()).getData();
              byte[] destData = newDataBuffer.getData();
              int j = 0;
              byte argb = 0;
              for (int i = 0; i < srcData.length; i++)
                   j = i * 4;
                   argb = (byte)(srcData[i] >> 24);
                   destData[j] = argb;
                   destData[j + 1] = 0;
                   destData[j + 2] = 0;
                   destData[j + 3] = 0;
              //Graphics2D g2 = dest.createGraphics();
              //g2.drawImage(source, 0, 0, null);
              //g2.dispose();
              return dest;
         }My apologies if that doesn't display correctly in the post.
    Basically, I create a BufferedImage the hard way, matching all the parameters of the image I get when I load in a PNG with alpha channel.
    The last bit, (for simplicity), just makes sure I copy over the alpha channel of old image to the new image, and assumes the color was black. This doesn't make any real speed difference.
    Now that runs lightning quick, but interestingly, see the bit I've commented out? The alternative to setting the ARGB values was to just draw the old image onto the new image. For a 640x512 image, this command (drawImage) took a whopping 36 SECONDS to complete! This may hint that the problem is to do with conversion.
    Anyhow, I got rather excited. The conversion went quickly. Here's the rub though, the image took 9 seconds to save using ImageIO.write, just the same as if I had never converted it. :(
    SOOOOOOOOOOOO... Why have I told you all this?
    Well, I guess I think it narrows dow the problem, but eliminates some solutions (to save people suggesting them).
    Bottom line, I still need to know why saving PNGs using ImageIO is so slow. Is there any other way to fix this, short of writing my own PNG writer, and indeed would THAT fix the issue?
    For the record, I have a piece of C code that does this in well under a second, so it can't JUST be a case of 'too much number-crunching'.
    I really would appreciate any help you can give on this. It's very frustrating.
    Thanks again. Robert Redwood.

Maybe you are looking for

  • Connection Time Out exception

    Hi All, I want to handle to Connection Time Out exception when displaying the BW Report in Portal. Please provide inputs. Also, is it possible to handle some look and feel of the BW Report from Portal itself. Regards Nikhil Bansal

  • When i run a sequence with ivi step types in simulation mode i get the error code number BFFA0015 - Types do not match.

    When i run the sequence with ivi step types in simulation mode i get the error Types do not mathc. The step that generates this error is an IviScope step type and is configured as a measurement. Th weird thing is that in real mode is working perfectl

  • Mac - help files not opening

    Somehow, the help files are not opening anymore. It opens the help viewer, but it is blank. I see the help files in the DW8 folder. How to reconnect? (The Flash, FW, and Contribute help works) Thanks so much, Hope

  • Anyone using itunes with XP MEDIA CENTER?

    I have had trouble installing itunes for DAYS! I kept getting the is not a win 32 app...did the troubleshooting but cant get the itunes uninstalled because it never got installed and cant find where to remove the set up. When I try to delete the TEMP

  • Forum interface event handling

    Perhaps an issue of performance, but I just noticed the following, which seems to indicate a misbehavior of the OTN forum software in regard to sequentially processing or canceling previous interface events. While browsing my communications page, I a