Problem displaying CMYK jpeg images

I have a problem with a CMYK jpeg image.
I know that about supported JPEGs in JRE - JCS_CMYK and JCS_YCCK are not supported directly.
And I found here how to load the image:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4799903
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5100094
I used both the suggestions described to load it, but when the image is displayed the colors are wrong, are very different from the one displayed in PhotoShop, for example.
Any suggestion are very appreciated. If it's necessary i can send you the image.
Roberto
Here is the code
package com.cesarer.example.crop;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
public class CroppingRaster extends JPanel
    BufferedImage image;
    Dimension size;
    Rectangle clip;
    boolean showClip;
    public CroppingRaster(BufferedImage image)
        this.image = image;
        size = new Dimension(image.getWidth(), image.getHeight());
        showClip = false;
    protected void paintComponent(Graphics g)
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        int x = (getWidth() - size.width)/2;
        int y = (getHeight() - size.height)/2;
        g2.drawImage(image, x, y, this);
        if(showClip)
            if(clip == null)
                createClip();
            g2.setPaint(Color.red);
            g2.draw(clip);
    public void setClip(int x, int y)
        // keep clip within raster
        int x0 = (getWidth() - size.width)/2;
        int y0 = (getHeight() - size.height)/2;
        if(x < x0 || x + clip.width  > x0 + size.width ||
           y < y0 || y + clip.height > y0 + size.height)
            return;
        clip.setLocation(x, y);
        repaint();
    public Dimension getPreferredSize()
        return size;
    private void createClip()
        clip = new Rectangle(140, 140);
        clip.x = (getWidth() - clip.width)/2;
        clip.y = (getHeight() - clip.height)/2;
    private void clipImage()
        BufferedImage clipped = null;
        try
            int w = clip.width;
            int h = clip.height;
            int x0 = (getWidth()  - size.width)/2;
            int y0 = (getHeight() - size.height)/2;
            int x = clip.x - x0;
            int y = clip.y - y0;
            clipped = image.getSubimage(x, y, w, h);
        catch(RasterFormatException rfe)
            System.out.println("raster format error: " + rfe.getMessage());
            return;
        JLabel label = new JLabel(new ImageIcon(clipped));
        JOptionPane.showMessageDialog(this, label, "clipped image",
                                      JOptionPane.PLAIN_MESSAGE);
    private JPanel getUIPanel()
        final JCheckBox clipBox = new JCheckBox("show clip", showClip);
        clipBox.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent e)
                showClip = clipBox.isSelected();
                repaint();
        JButton clip = new JButton("clip image");
        clip.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent e)
                clipImage();
        JPanel panel = new JPanel();
        panel.add(clipBox);
        panel.add(clip);
        return panel;
    public static void main(String[] args) throws IOException
         File file = new File("src/ABWRACK_4C.jpg");
         // Find a JPEG reader which supports reading Rasters.
        Iterator readers = ImageIO.getImageReadersByFormatName("JPEG");
        ImageReader reader = null;
        while(readers.hasNext()) {
            reader = (ImageReader)readers.next();
            if(reader.canReadRaster()) {
                break;
     // Set the input.
        ImageInputStream input =
            ImageIO.createImageInputStream(file);
        reader.setInput(input);
        Raster raster = reader.readRaster(0, null);
         BufferedImage bi = new BufferedImage(raster.getWidth(),
                raster.getHeight(),
                BufferedImage.TYPE_4BYTE_ABGR);
         // Set the image data.
         bi.getRaster().setRect(raster);
        // Cropping test = new Cropping(ImageIO.read(file));
         CroppingRaster test = new CroppingRaster(bi);
        ClipMoverRaster mover = new ClipMoverRaster(test);
        test.addMouseListener(mover);
        test.addMouseMotionListener(mover);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new JScrollPane(test));
        f.getContentPane().add(test.getUIPanel(), "South");
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
class ClipMoverRaster extends MouseInputAdapter
    CroppingRaster cropping;
    Point offset;
    boolean dragging;
    public ClipMoverRaster(CroppingRaster c)
        cropping = c;
        offset = new Point();
        dragging = false;
    public void mousePressed(MouseEvent e)
        Point p = e.getPoint();
        if(cropping.clip.contains(p))
            offset.x = p.x - cropping.clip.x;
            offset.y = p.y - cropping.clip.y;
            dragging = true;
    public void mouseReleased(MouseEvent e)
        dragging = false;
    public void mouseDragged(MouseEvent e)
        if(dragging)
            int x = e.getX() - offset.x;
            int y = e.getY() - offset.y;
            cropping.setClip(x, y);
}

The loading process It takes about 10 seconds, and every repaint it takes the same time.The painting yes, the loading no. It shouldn't take much more time to load the image then an ordinary JPEG. In particular, your now using a "natively accelerated" JPEG image reader, so it should take less time on average to load any JPEG. 10 seconds is absurd. Are you sure your not including the drawing time in that figure?
- Another problem: JAI-ImageIO is not available for MAC OS X platform.This is somewhat true. You can take the imageio.jar file and package it together with your program (adding it to the class path). This will give you most of the functionality of JAI-ImageIO; in particular the TIFFImageReader. You just won't be able to use the two natively accelerated ImageReaders that comes with installing.
Right now, you're using the accelerated CLibJPEGImageReader to read the image. You can't use this image reader on the MAC, so you have to take the approach mentioned in the 2nd bug report you originally posted (i.e. use an arbitrary CMYK profile).
The conversion is too long more than 30 seconds.The code you posted could be simplified to
BufferedImage rgbImage = new BufferedImage(w,h,
            BufferedImage.3_BYTE_BGR);
ColorConvertOp op = new ColorConvertOp(null);
op.filter(cmykImage,rgbImage);But again, 30 seconds is an absurd value. After a little preparation, converting from one ICC_Profile to another is essentially a look up operation. What does,
System.out.println(cmykImage.getColorModel().getColorSpace());print out? If it's not an instance of ICC_ColorSpace, then I can understand the 30 seconds. If it is, then something is dreadfully wrong.
the RGB bufferedImage that i get after the transformation when it is displayed is much more brightThis is the "one last problem that pops up" that I hinted at. It's because some gamma correction is going on in the background. I have a solution, but it's programming to the implementation of the ColorConvertOp class and not the API. So I'm not sure about its portability between java versions or OS's.
import javax.swing.*;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import javax.imageio.ImageIO;
import java.io.File;
public class CMYKTest {
     public static void main(String[] args) throws Exception{
        long beginStamp, endStamp;
        //load image
        beginStamp = System.currentTimeMillis();
        BufferedImage img = ImageIO.read(/*cmyk image file*/);
        endStamp = System.currentTimeMillis();
        System.out.println("Time to load image: " + (endStamp-beginStamp));
        //color convert
        BufferedImage dest = new BufferedImage(img.getWidth(),
                                               img.getHeight(),
                                               BufferedImage.TYPE_3BYTE_BGR);
        beginStamp = System.currentTimeMillis();
        sophisticatedColorConvert(img,dest);
        endStamp = System.currentTimeMillis();
        System.out.println("Time to color convert: " + (endStamp-beginStamp));
        //display
        JFrame frame = new JFrame();
        frame.setContentPane(new JScrollPane(new JLabel(new ImageIcon(dest))));
        frame.setSize(500,500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    public static BufferedImage sophisticatedColorConvert(BufferedImage src,
                                                          BufferedImage dst) {
        ICC_ColorSpace srcCS =
                (ICC_ColorSpace) src.getColorModel().getColorSpace();
        ICC_Profile srcProf = srcCS.getProfile();
        byte[] header = srcProf.getData(ICC_Profile.icSigHead);
        intToBigEndian(ICC_Profile.icSigInputClass,header,12);
        srcProf.setData(ICC_Profile.icSigHead,header);
        ColorConvertOp op = new ColorConvertOp(null);
        return op.filter(src, dst);
    private static void intToBigEndian(int value, byte[] array, int index) {
            array[index]   = (byte) (value >> 24);
            array[index+1] = (byte) (value >> 16);
            array[index+2] = (byte) (value >>  8);
            array[index+3] = (byte) (value);
}

Similar Messages

  • How can I load a CMYK jpeg image

    How can I load a CMYK jpeg image (originally saved from Photoshop) and then
    turn it into an rgb BufferedImage, in order to display it on screen in an
    applet?
    I first tried ImageIO.read(), but that does not work for cmyk jpegs. I then
    looked into the com.sun.image.codec.jpeg package, and tried methods like
    decodeAsBufferedImage() and decodeAsRaster().
    The first one (decodeAsBufferedImage) returned an image, but it seems that
    it was interpreted as an ARGB, and the colors were incorrect.
    I then read the documentation which (amongst many other things) stated that
    "If the user needs better control over conversion, the user must request the
    data as a Raster and handle the conversion of the image data themselves."
    This made sense, so I took to decodeAsRaster(), only to find that I could
    not figure out how to carry out the desired conversion.
    Of course, I have looked into the documentation for BufferedImage, Raster,
    ColorModel, ColorSpace etc, but after a while I was lost. (Before I got lost
    I read that you can convert images with the help of methods like toRGB,
    toCIEXYZ.)
    I have a feeling that this is probably pretty simple if you just know how to
    do it, but I sure would need some directions here.
    Any help would be appreciated. Thanks.

    You can either use the "Place" command from the main menu, under "File", or you can just open it, select the move tool "V", the click in the image and drag it to the other file's tab.

  • I see inconsistent ImageNew() failures for CMYK Jpeg Images  (CF10)

    Weird problem.
    I have a set of test cases that pass just fine loading a known CMYK jpeg via ImageNew().  Later, with no restart of the app server, these same test cases fail.  Again, after a while, the test case passes again.  I've dug into the Java a little bit, and I wonder if the ImageReader implementation being used doesn't switch out once in a while -- like maybe a hashtable of ImageReaders reorders or something.
    I know the CMYK is only partially supported, but I could get data with ImageNew and ImageInfo showing it was a CMYK file, then later on, it would throw "Image Not Supported" errors.
    Anybody have knowledge of these inner workings to provide some insight?  Smells a bit like a bug to me, but I can't consistently replicate it.
    -Dave

    From what I can tell, it does appear to be a bug.  I have submitted a bug report to Adobe on it.
    https://bugbase.adobe.com/index.cfm?event=bug&id=3596008
    What seems to be occurring is that coldfusion.image.ImageReader is trying to find the CLibJPEGImageReader class from the collection returned by javax.imageio.ImageIO.getImageReadersByFormatName("jpeg").  This works fine if it is the first object returned in the collection, but if not, it will return another JPEG ImageReader that does not support CMYK images.  I have two systems (both RedHat) which are currently in each state.  One has the CLibJPEGImageReader as the first element in the ImageReader collection, and in the other, it is the second element in the collection.  The code below will work fine when the correct reader is found, but not when it isn't the first element in the collection.

  • Problem while encoding JPEG image from JFrame paintComponent in a servlet

    Hello!
    I m developing webapplication in which I made one servlet that calls JFrame developed by me, and then encoding into JPEG image to send response on client browser. I m working on NetBeans 5.5 and the same code runs well. But my hosting server is Linux and I m getting the following error:
    java.awt.HeadlessException:
    No X11 DISPLAY variable was set, but this program performed an operation which requires it.
         java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:159)
         java.awt.Window.<init>(Window.java:406)
         java.awt.Frame.<init>(Frame.java:402)
         java.awt.Frame.<init>(Frame.java:367)
         javax.swing.JFrame.<init>(JFrame.java:163)
         pinkConfigBeans.pinkInfo.pinkModel.pinkChartsLib.PinkChartFrame.<init>(PinkChartFrame.java:36)
         pinkConfigBeans.pinkController.showLastDayRevenueChart.processRequest(showLastDayRevenueChart.java:77)
         pinkConfigBeans.pinkController.showLastDayRevenueChart.doGet(showLastDayRevenueChart.java:107)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    note The full stack trace of the root cause is available in the Apache Tomcat/5.5.25 logs.
    I m building the application in NetBeans and when runs then it runs well, even while browsing from LAN. But when I place the web folder creted under buil directory of NetBeans in the Tomcat on Linux, then it gives above error.
    Under given is the servlet code raising exception
    response.setContentType("image/jpeg"); // Assign correct content-type
    ServletOutputStream out = response.getOutputStream();
    /* TODO GUI output on JFrame */
    PinkChartFrame pinkChartFrame;
    pinkChartFrame = new PinkChartFrame(ssnGUIAttrInfo.getXjFrame(), ssnGUIAttrInfo.getYjFrame(), headingText, xCordText, yCordText, totalRevenueDataList);
    pinkChartFrame.setTitle("[::]AMS MIS[::] Monthly Revenue Chart");
    pinkChartFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    //pinkChartFrame.setVisible(true);
    //pinkChartFrame.plotDataGUI();
    int width = 760;
    int height = 460;
    try {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    pinkChartFrame.pinkChartJPanel.paintComponent(g2);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    encoder.encode(image);
    } catch (ImageFormatException ex) {
    ex.printStackTrace();
    response.sendRedirect("index.jsp");
    } catch (IOException ex) {
    ex.printStackTrace();
    response.sendRedirect("index.jsp");
    out.flush();
    Do resolve anybody!
    Edited by: pinkVag on Oct 15, 2007 10:19 PM

    >
    I m developing webapplication in which I made one servlet that calls JFrame developed by me, and then encoding into JPEG image to send response on client browser. I m working on NetBeans 5.5 and the same code runs well. But my hosting server is Linux and I m getting the following error:
    java.awt.HeadlessException: >That makes sense. It is saying that you cannot open a JFrame in an environment (the server) that does not support GUIs!
    To make this so it will work on the server, it will need to be recoded so that it uses the command line only - no GUI.
    What is it exactly that PinkChartFrame is generated an image of? What does it do? (OK probably 'generate a chart') But what APIs does it use (JFreeChart or such)?

  • Problem importing some jpeg images

    **** all
    For some reason I cant import selected jpeg images, about 75% of them are grayed out for some reason, the images are jpegs I have collected on line and are the only images I seem to have a problem with.
    Any idea way ?
    Thanks

    yes I have the actual image, I found the problem .
    they where all grayed out cause of the image size, I downloaded desktop images.
    I'm glad I worked it out cause I'm using these images as backgrounds and, have 487 of them. I ran them through easybatchphoto and resized the width on all of them to 800. now they all work fine.

  • Photoshop CS6  - problem displaying CMYK files in the project RGB

    Hello!
    I have a problem in 64 bit Photoshop CS6 - a new file (RGB, 72 dpi, no color profiles, mode 8-bit) images I put smart objects (images, CMYK, 300 dpi, 8-bit mode) wanting to build a small presentation for the web. These images in CMYK in some places have black spots pixelowe mainly in places where there is a gradient, or green. When you export a file to jpg's no black spots.
    In other applications, this problem does not exist. Restarted the program recording it again but the problem has not gone away. Photoshop settings are standard.
    I'm working on Win Pro 7, a very good computer.
    What do I do? Help me: (

    I am not entirely sure I understand you, but it sounds like it could be graphic card related... possibly at least. Could you post a screen-shot of how the problem looks?

  • Problem displaying binary tif image from rfc

    Hello All,
    I am trying to display an image that is returned from RFC as binary image
    <b><u>Context description:</u></b>
    Context Node From RFC -  Out_Et_Image node type tbl1024
    Node element Line
    As I understand the node is representing a byte array and each Line element i a part of the array .
    <b><u><i>i did</i></u></b>
    <b>1. merge it into one byte array :</b>
    int ArrayTot = 0 ;
    for ( i =0;i<wdContext.nodeOut_Et_Image().size();i++){
         ArrayTot = ArrayTot+wdContext.nodeOut_Et_Image().getOut_Et_ImageElementAt(i).getLine().length     ;
         final byte[] pictureContentTemp1 = new byte[ArrayTot];
         for ( i =0;i<wdContext.nodeOut_Et_Image().size();i++){
              if(i>0){
                   j=j+wdContext.nodeOut_Et_Image().getOut_Et_ImageElementAt(i-1).getLine().length;
                   System.arraycopy(wdContext.nodeOut_Et_Image().getOut_Et_ImageElementAt(i).getLine(),0,
                        pictureContentTemp1,0,wdContext.nodeOut_Et_Image().getOut_Et_ImageElementAt(i).getLine().length     );
              }else{
                   j=wdContext.nodeOut_Et_Image().getOut_Et_ImageElementAt(i).getLine().length;
                   System.arraycopy(wdContext.nodeOut_Et_Image().getOut_Et_ImageElementAt(i).getLine(),0,
                                       pictureContentTemp1,j,wdContext.nodeOut_Et_Image().getOut_Et_ImageElementAt(i).getLine().length     );
    <u><b>2. using the IWDCachedWebResource to generate and display it</b></u>
    IWDCachedWebResource resource = WDWebResource.getWebResource
    (pictureContentTemp1,
    WDWebResourceType.GIF_IMAGE);
    resource.setResourceName("pic");
    try{
    IWDWindow window = wdComponentAPI.getWindowManager().
    createExternalWindow(resource.getURL(), "gggg", true);
    // Eliminate some features of the window
    window.removeWindowFeature(WDWindowFeature.ADDRESS_BAR);
    window.removeWindowFeature(WDWindowFeature.MENU_BAR);
    window.removeWindowFeature(WDWindowFeature.STATUS_BAR);
    window.removeWindowFeature(WDWindowFeature.TOOL_BAR);
    window.setWindowSize(780,430);
    window.setWindowPosition(20,140);
    window.open();
    }catch (Exception e){
         wdComponentAPI.getMessageManager().reportException(e.getLocalizedMessage(),false);
    The problem is that I get a corrupted file and i cant see or open it .
    Some more details:
    The original image size is 42,234 bytes
    i get from the RFC after merging the array 43,008 bytes i think that the extra bytes that a get are the problem , but i don't have any idea how to get rid of them or solve the problem .
    My WAS version is nw04 sp19
    Does any one encounter this problem? Or can guide me what to do?
    Thanks
    Ronen

    Try this VI (It's from "Image Acquisition and Processing with LabVIEW" - see for more details...
    cheers,
    Christopher
    Christopher G. Relf
    Certified LabVIEW Developer
    [email protected]
    International Voicemail & Fax: +61 2 8080 8132
    Australian Voicemail & Fax: (02) 8080 8132
    EULA
    1) This is a private email, and although the views expressed within it may not be purely my own, unless specifically referenced I do not suggest they are necessarily associated with anyone else including, but not limited to, my employer(s).
    2) This email has NOT been scanned for virii - attached file(s), if any, are provided as is. By copying, detaching and/or opening attached file
    s, you agree to indemnify the sender of such responsibility.
    3) Because e-mail can be altered electronically, the integrity of this communication cannot be guaranteed.
    >
    Copyright © 2004-2015 Christopher G. Relf. Some Rights Reserved. This posting is licensed under a Creative Commons Attribution 2.5 License.
    Attachments:
    Image_Browser-Selector_Example.llb ‏107 KB

  • Help with SWFObject2, problem with display of alternate image

    I'm trying to use SWFObject2 dynamic publishing version to test the visitors browser for flash pluggin and the version.
    I want to only show my flash image if the browser finds the flash plug in and it supports the correct version of flash for my banner, otherwise I want to display a jpeg image in its place.
    When flash support is available in my browser the flash image is displayed, no problems. But when Javascript or flash plugin support is not available and my alternate image jpeg is displayed something wierd happens and i would appreciate any help on this:
    The image is displayed but is pushed to the right of the screen and it seems to have a box behind the image, the edge of the box is only visable and changes colour on rollove like it wants to be clicked, obviously i cannot see what the box is because the image covers it. There is nothing wrong with my image, i put that in place first and tested it loaded ok before i added the SWFObject code and file.
    My code is below:
    <script type="text/javascript" src="Scripts/swfobject.js"></script>
    <script type="text/javascript">
    swfobject.embedSWF("advertise_banner.swf", "altContent", "468", "60", "6.0.0", "expressinstall.swf");
    </script>
    </head>
    <body>
    <div id="wrapAltContent">
    <div id="altContent">
    <a href="advertise_banner.php?ad=y">
    <img src="Images/advertise_banner.jpg" alt="Image linking to information on  advertising a banner ad on Choose Almeria" />
    </a>
    </div>
    </div>
    Looking forward to replies.

    Hi,
    Is this your question still relevant? If yes, did you study already this for example?
    http://code.google.com/p/swfobject/wiki/documentation
    Hans-G.

  • Converting cmyk compressed images to rgb compressed format

    Hi,
    I need some help in converting of CMYK images to RGB images. I got some sample code from internet but I get some run time exceptions with that and I'm not able to figure out the reason for the same. Pls help me in fixing the same. Any help will be sincerely appreicated.
    The code is given below :
    import java.awt.image.*;
    import java.awt.image.renderable.*;
    import java.awt.color.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    import javax.media.jai.*;
    import com.sun.image.codec.jpeg.*;
    public class CMYKTest1 {
      public static void main(String args[]) throws Exception{
         RenderedOp op = JAI.create("fileload", "Kristopher Brock LOGO.jpg");
         ColorModel rgbcm = op.getColorModel();
         ICC_Profile profile = ICC_Profile.getInstance("CMYK.pf");
    //     ICC_Profile profile = ICC_Profile.getInstance(ColorSpace.TYPE_CMYK);
         ICC_ColorSpace icp = new ICC_ColorSpace(profile);
         ColorModel colorModel =
              RasterFactory.createComponentColorModel(op.getSampleModel().getDataType(),
                                                                icp,
                                                                false,
                                                                false,
                                                                Transparency.OPAQUE);
         ImageLayout il = new ImageLayout();
         il.setSampleModel(colorModel.createCompatibleSampleModel(op.getWidth(),
                                                                                op.getHeight()));
         RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, il);
         ParameterBlock pb = new ParameterBlock();
         pb.addSource(op).add(colorModel);
         op = JAI.create("ColorConvert", pb, hints);
         pb = new ParameterBlock();
         pb.addSource(op).add(rgbcm);
         il = new ImageLayout();
         il.setSampleModel(rgbcm.createCompatibleSampleModel(op.getWidth(),
                                                                          op.getHeight()));
         hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, il);
         op = JAI.create("ColorConvert", pb, hints);
         JAI.create("filestore", op, "earthrgb.jpg", "JPEG", null);
         BufferedImage img = op.getAsBufferedImage(null, null);
         OutputStream fout = new FileOutputStream("earthrgb1.jpg");
         JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fout);
         JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img);
         param.setQuality(1, false);
         param.setXDensity(300);
         param.setYDensity(400);
         encoder.encode(img, param);
         fout.close();
    }I get the following error:
    Caused by: java.lang.IllegalArgumentException: Numbers of source Raster bands and source color space components do not match
         at java.awt.image.ColorConvertOp.filter(Unknown Source)
         at com.sun.media.jai.opimage.ColorConvertOpImage.computeRectNonColorSpaceJAI(ColorConvertOpImage.java:373)
         at com.sun.media.jai.opimage.ColorConvertOpImage.computeRect(ColorConvertOpImage.java:290)
         at javax.media.jai.PointOpImage.computeTile(PointOpImage.java:914)
         at com.sun.media.jai.util.SunTileScheduler.scheduleTile(SunTileScheduler.java:904)
         at javax.media.jai.OpImage.getTile(OpImage.java:1129)
         at javax.media.jai.PointOpImage.computeTile(PointOpImage.java:911)
         at com.sun.media.jai.util.SunTileScheduler.scheduleTile(SunTileScheduler.java:904)
         at javax.media.jai.OpImage.getTile(OpImage.java:1129)
         at com.sun.media.jai.codecimpl.JPEGImageEncoder.encode(JPEGImageEncoder.java:173)
         at com.sun.media.jai.opimage.EncodeRIF.create(EncodeRIF.java:70)
         ... 24 more
    Error: One factory fails for the operation "filestore"
    Occurs in: javax.media.jai.ThreadSafeOperationRegistry
    java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at javax.media.jai.FactoryCache.invoke(FactoryCache.java:122)
         at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1674)
         at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:473)
         at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:332)
         at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:819)
         at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:867)
         at javax.media.jai.RenderedOp.getRendering(RenderedOp.java:888)
         at javax.media.jai.JAI.createNS(JAI.java:1099)
         at javax.media.jai.JAI.create(JAI.java:973)
         at javax.media.jai.JAI.create(JAI.java:1668)
         at CMYKTest1.main(CMYKTest1.java:79)
    Caused by: javax.media.jai.util.ImagingException: All factories fail for the operation "encode"
         at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1687)
         at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:473)
         at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:332)
         at com.sun.media.jai.opimage.FileStoreRIF.create(FileStoreRIF.java:138)
         ... 15 moreThanks & Regards,
    Magesh.

    The following code converts an cmyk jpeg image into an rgb jpeg image.
    The only problem if this code is that it loads the whole image in memory and thus you'll need a lot of RAM when converting large images. For example, it take around 300 MB to convert a 3000*3800px image (this is a 5MB jpeg image when compressed on disk).
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGEncodeParam;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageReader;
    import javax.imageio.stream.ImageInputStream;
    import javax.imageio.metadata.IIOMetadata;
    import javax.imageio.metadata.IIOMetadataNode;
    import java.util.*;
    import java.io.*;
    import java.awt.image.*;
    import java.awt.*;
    import java.awt.color.ColorSpace;
    import org.w3c.dom.NodeList;
    public class Test {
        public static void main(String[] args) throws Exception {
            BufferedImage i1 = readImage(new File("cmyk.jpg"));
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File("rgb.jpg")));
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(i1);
            param.setQuality(1, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(i1);
        public Test() {
        // extract metadata
        public static BufferedImage readImage(File file) throws IOException {
            // Get an ImageReader.
            ImageInputStream input = ImageIO.createImageInputStream(file);
            Iterator readers = ImageIO.getImageReaders(input);
            if (readers == null || !readers.hasNext()) {
                throw new RuntimeException("No ImageReaders found");
            ImageReader reader = (ImageReader) readers.next();
            reader.setInput(input);
            String format = reader.getFormatName();
            if ("JPEG".equalsIgnoreCase(format) || "JPG".equalsIgnoreCase(format)) {
                IIOMetadata metadata = reader.getImageMetadata(0);
                String metadataFormat = metadata.getNativeMetadataFormatName();
                IIOMetadataNode iioNode = (IIOMetadataNode) metadata.getAsTree(metadataFormat);
                NodeList children = iioNode.getElementsByTagName("app14Adobe");
                if (children.getLength() > 0) {
                    iioNode = (IIOMetadataNode) children.item(0);
                    int transform = Integer.parseInt(iioNode.getAttribute("transform"));
                    Raster raster = reader.readRaster(0, reader.getDefaultReadParam());
                    if (input != null) {
                        input.close();
                    reader.dispose();
                    return createJPEG4(raster, transform);
            throw new RuntimeException("No ImageReaders found");
         * Java's ImageIO can't process 4-component
         * images
         * <p/>
         * and Java2D can't apply AffineTransformOp
         * either,
         * <p/>
         * so convert raster data to
         * RGB.
         * <p/>
         * Technique due to MArk
         * Stephens.
         * <p/>
         * Free for any
         * use.
        private static BufferedImage createJPEG4(Raster raster, int xform) {
            int w = raster.getWidth();
            int h = raster.getHeight();
            byte[] rgb = new byte[w * h * 3];
            // if (Adobe_APP14 and transform==2) then YCCK else CMYK
            if (xform == 2) {    // YCCK -- Adobe
                float[] Y = raster.getSamples(0, 0, w, h, 0, (float[]) null);
                float[] Cb = raster.getSamples(0, 0, w, h, 1, (float[]) null);
                float[] Cr = raster.getSamples(0, 0, w, h, 2, (float[]) null);
                float[] K = raster.getSamples(0, 0, w, h, 3, (float[]) null);
                for (int i = 0, imax = Y.length, base = 0; i < imax; i++, base += 3) {
                    float k = 220 - K, y = 255 - Y[i], cb = 255 - Cb[i], cr = 255 - Cr[i];
    double val = y + 1.402 * (cr - 128) - k;
    val = (val - 128) * .65f + 128;
    rgb[base] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);
    val = y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128) - k;
    val = (val - 128) * .65f + 128;
    rgb[base + 1] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);
    val = y + 1.772 * (cb - 128) - k;
    val = (val - 128) * .65f + 128;
    rgb[base + 2] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);
    else {
    // assert xform==0: xform;
    // CMYK
    int[] C = raster.getSamples(0, 0, w, h, 0, (int[]) null);
    int[] M = raster.getSamples(0, 0, w, h, 1, (int[]) null);
    int[] Y = raster.getSamples(0, 0, w, h, 2, (int[]) null);
    int[] K = raster.getSamples(0, 0, w, h, 3, (int[]) null);
    for (int i = 0, imax = C.length, base = 0; i < imax; i++, base += 3) {
    int c = 255 - C[i];
    int m = 255 - M[i];
    int y = 255 - Y[i];
    int k = 255 - K[i];
    float kk = k / 255f;
    rgb[base] = (byte) (255 - Math.min(255f, c * kk + k));
    rgb[base + 1] = (byte) (255 - Math.min(255f, m * kk + k));
    rgb[base + 2] = (byte) (255 - Math.min(255f, y * kk + k));
    // from other image types we know InterleavedRaster's can be
    // manipulated by AffineTransformOp, so create one of
    // those.
    raster = Raster.createInterleavedRaster(new DataBufferByte(rgb, rgb.length), w, h, w * 3, 3, new int[]{0, 1, 2}, null);
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    ColorModel cm = new ComponentColorModel(cs, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
    return new BufferedImage(cm, (WritableRaster) raster, true, null);

  • CMYK Jpegs appear lighter and desaturated

    Hey everyone,
    I'm having an annoying issue with my CMYK images. I work for a marketing co. that's primarily print, and after uploading my images to our online storage interface (we use Egnyte), the jpegs appear "milky" or lighter and desaturated than what they do on my screen and in Photoshop. I've tested tiff, jpeg and pdf and they all look fine on my screen, but the jpeg and tiff appear "milky" only on my collegue's screen, but the pdf is fine. She is on a Mac, I'm on PC, and no matter how I open the images, whether I redownload them from the web, or open them straight from my hd, they appear just fine.
    Thanks for any and all help
    Andy

    How are you viewing those JPEGS?
    Most web browsers do not know how to display CMYK JPEGs, much less how to use the profiles from those images.
    Acrobat does know how to display CMYK, and use color profiles.

  • Move a jpeg image within a picture control

    I am having problems moving a jpeg image inside a picture control with my arrow buttons.
    any help would be great thanks
    Harold Timmis
    [email protected]
    Orlando,Fl
    *Kudos always welcome
    Solved!
    Go to Solution.
    Attachments:
    picfun.vi ‏17 KB
    ball.jpg ‏2 KB

    Hi Harold,
    Things are hooked up wrong....
    (Also, you don't really want to read the same file with each repeat. Once is enough! )
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    picfunMOD.vi ‏13 KB

  • JPEG image with interlacing / progression

    Why is bug 4675817
    http://developer.java.sun.com/developer/bugParade/bugs/4675817.html
    closed?
    I'm using J2SDK1.4.2 and with JWS my application just quits when trying to display a JPEG image with interlacing / progression.

    This is an infuriating bug; I couldn't believe how much time I wasted before I found the bugreports � by which time I was ready to hang, draw & quarter the guilty party (or the nearest sun employee).
    The bug seemed closed against a similar bugreport, and this in turn has been closed against Tiger � which is 1.5 the next upcoming major release; which will probably happen next year now.
    - Richard

  • ICC profile to convert RGB to CMYK,   jpeg is ok, png format have a problem

    When I use ICC profile to convert RGB to CMYK, jpeg format is ok, but png format have a problem.the color is lossy.
    It means, the png file color is shallow than jpeg file after convert.Could anybody help me?
    thanks
    source code
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.Iterator;
    import javax.imageio.IIOImage;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageTypeSpecifier;
    import javax.imageio.ImageWriteParam;
    import javax.imageio.ImageWriter;
    import javax.imageio.metadata.IIOMetadata;
    import javax.imageio.metadata.IIOMetadataNode;
    import javax.imageio.stream.ImageOutputStream;
    import org.w3c.dom.Node;
    import com.sun.image.codec.jpeg.ImageFormatException;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGEncodeParam;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    public class TestImage {
         public static void main(String args[]) throws ImageFormatException, IOException{
              BufferedImage readImage = null;
              try {
                  readImage = ImageIO.read(new File("C:\\TEST.jpg"));
              } catch (Exception e) {
                  e.printStackTrace();
                  readImage = null;
              readImage = CMYKProfile.getInstance().doChColor(readImage);
              writeImage(readImage, "C:\\TEST_after_.jpg", 1.0f);
        protected static String getSuffix(String filename) {
            int i = filename.lastIndexOf('.');
            if(i>0 && i<filename.length()-1) {
                return filename.substring(i+1).toLowerCase();
            return "";
        protected static void writeImage(BufferedImage image, String filename, float quality) {
            Iterator writers = ImageIO.getImageWritersBySuffix(getSuffix(filename));
            System.out.println("filename�F"+filename);
            if (writers.hasNext()) {
                ImageWriter writer = (ImageWriter)writers.next();
                try {
                    ImageOutputStream stream
                        = ImageIO.createImageOutputStream(new File(filename));
                    writer.setOutput(stream);
                    ImageWriteParam param = writer.getDefaultWriteParam();
                    if (param.canWriteCompressed()) {
                        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);//NO COMPRESS
                        param.setCompressionQuality(quality);
                    } else {
                        System.out.println("Compression is not supported.");
                    IIOMetadata metadata = null;
                    if(getSuffix(filename).equals("png") || getSuffix(filename).equals("PNG")){
                         ImageTypeSpecifier imageTypeSpecifier = new ImageTypeSpecifier(image);
                         metadata = writer.getDefaultImageMetadata(imageTypeSpecifier, param);
                            String sFormat = "javax_imageio_png_1.0";
                            Node node = metadata.getAsTree(sFormat);
                            IIOMetadataNode gammaNode = new IIOMetadataNode("gAMA");
                            String sGamma = "55556";
                            gammaNode.setAttribute("value", sGamma);
                            node.appendChild(gammaNode);
                            metadata.setFromTree(sFormat, node);
                    writer.write(null, new IIOImage(image, null, metadata), param);
                    writer.dispose();
                    return;
                } catch (IOException ex) {
                    ex.printStackTrace();
    }

    Hi,
    I am having similar problems. I have read somewhere that png format can not handle CMYK colorspace anyway, which I find odd (and plainly stupid IM(NS)HO) which would mean that converting to RGB and therefore using profiles is mandatory.
    May be you should check if the internal format of the png files claims it is RGB or CMYK (using ImageMagick's "identify" command for example).
    HTH
    JG

  • Please help-image problem (display)

    Can someone please help with this?
    I keep receiving an error (below) while trying to execute the code...
    2001-07-19 11:55:02 - Ctx( /dev ): IOException in: R( /dev + /servlet/getImage + null) Connection reset by peer: socket write error
    My setup is Tomcat 3.2
    JDBC: Oracle's classes12.zip
    JDK: Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.0-C)
    Java HotSpot(TM) Client VM (build 1.3.0-C, mixed mode)
    I have copied my simple code below for review:
    package lmmfcd.images;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.sql.*;
    import javax.servlet.jsp.*;
    import javax.servlet.jsp.tagext.*;
    import org.apache.jasper.runtime.*;
    import java.beans.*;
    import org.apache.jasper.JasperException;
    public class getImages extends HttpServlet
         public void doGet(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException
              //Grabs and assigns the PageContext
                   JspFactory _jspxFactory = null;
                   PageContext pageContext = null;
                   Object page = this;
                   _jspxFactory = JspFactory.getDefaultFactory();
                   pageContext = _jspxFactory.getPageContext(this, request, response,
                        "", true, 8192, true);
              //End of the PageContext Stuff
              Connection conn = (Connection)pageContext.findAttribute("conn");
                   try
                        ResultSet rset = null;
                        String queryCmd =
                                  "SELECT     image "+
                                  "FROM          sgps.images "+
                                  "WHERE          pn = '13507028' "+
                                  " AND          pic_num = '1' ";
                        Statement stmt = conn.createStatement();
                        rset = stmt.executeQuery(queryCmd);
                        rset.next();
                        Blob blob = null;
                        blob = rset.getBlob("image");
                        response.setContentType("image/jpeg");
                        byte[] ba = blob.getBytes(1, (int)blob.length());
                        System.out.println("just above OutputStream");
                        response.getOutputStream().write(ba, 0, ba.length);
                        response.getOutputStream().flush();
                        response.getOutputStream().close();                    
                   catch(SQLException e)
                        throw new ServletException("Problem");
    }

    It compiled okay, but still displayed the broken image as the result....
              if (rset != null)
                   try
                        BLOB blob = null;
                        blob = (BLOB)rset.getObject("image");
                        response.setContentType("image/jpeg");
                        InputStream in = rset.getBinaryStream("image");
                        //Have also used:
                        //InputStream in = blob.getBinaryStream();
                        OutputStream out = response.getOutputStream();
                        byte b;
                        while ((b = (byte)in.read()) != 1)
                             out.write(b);
                        in.close();
                        out.flush();
                        out.close();
                   catch(SQLException e)
                        throw new ServletException("Problem");
              }

  • Jpeg image loaded with Loader- loadBytes() does not display when app is deployed on remote server

    I am loading a JPEG  image from the server, using the Loader->loadBytes() and that works when the app is deployed under my local Tomcat server.  When I deploy it on other servers the image is not displayed,  instead of the image I see II*
    On the server side I have java, Spring, BlazeDs and I use RemoteObject on the client.
    The code that loads the image looks like below:
    private function imageLoadResultHandler(event:ResultEvent):void {
        var result:ArrayCollection = event.result as ArrayCollection
        var bytes : ByteArray = result.getItemAt(0) as ByteArray;
        _loader = new Loader();
        _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);
        _loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loaderFaultHandler);
        _loader.loadBytes(bytes);
    private function loaderCompleteHandler(event:Event):void {
        var loaderInfo:LoaderInfo = event.currentTarget as LoaderInfo;
        var img:Image = new Image();
        img.source = loaderInfo.content;
        myPanel.addChild(img);
    <mx:RemoteObject id="ro" destination="imageLoadService">
         <mx:method name="loadImage" result="imageLoadResultHandler(event)" fault="faultHandler(event)" />
    </mx:RemoteObject>
    Any help with this problem is much appreciated.
    Thank you,
    Lumi Velicanu

    Hi Dmitri,
    Thank you for the prompt reply, your question about the jpeg content was a helpful pointer.
    I solved the problem, it had nothing to do with flex, it was all on the java side. The image was obtained from converting a TIFF to a JPEG, the conversion was failing and the flex loader was receiveing a tiff and it did not know how to display it.
    The java problem was kind of interesting, I'll post it here as an FYI in case anybody cares :
    On my server the first writer returned by ImageIO was an instance of JPEGImageWriter and on the other servers was CLibJPEGImageWriter. And it happens that  only JPEGImageWrite can write the type of TIFF that we are having.
    The fix was to iterate through all the writers and pick the instace of JPEGImageWrite, instead of the first one found.
    Lumi

Maybe you are looking for

  • Descaso com a comunidade de desenvolvedores do Brasil

    Gostaria de compartilhar com o grupo uma opinião pessoal. Posso estar enganado pois, não sou o dono da verdade. Sou desenvolvedor ABAP e fui baixar a versão SAP NetWeaver Application Server ABAP 7.4 on SAP MaxDB - Trial Edition para uma avaliação da

  • Retrieving .txt file from jar for an applet

    I guess this is a newbie question but i checked the tutorial sessions and i am doing exactly what it says there but still...no luck: I'm trying to access a .txt. file stored in the .jar file where my applet .class file is stored. I'm using: String s

  • Provision for zonewise budget entry  in APO-DP

    Hi experts Is it possible to enter zonewise (we have four sales zones) budget in demand planning ? Forecast to be done against budget. Could you pl. explain step by step This is very urgent and help any one pl. Thanks in advance SR Chandu 970 440 451

  • Adobe Flash Pro CS6 -- cursor and focus issues

    This is OS specific as it works fine in the Snow Leopard. I am having issues with nearly everything involved with switching between apps / focusing on text windows / getting the cursor to appear where I click / etc since upgrading to Mountian Lion/Ma

  • Help  IPOD problem

    I have a IPOD photo 20Gb. The problem I have is that the IPOD seems to be death, the Apple logo and menu reappear (and my pc sess it) only if I slide the hold switch to on (so the ipod is off). If I put back the switch to off, the screens goes black