This discussion is archived
9 Replies Latest reply: Feb 8, 2013 9:23 AM by Maxideon RSS

I met a question about  conversion the png into jpeg

979385 Newbie
Currently Being Moderated
Hi all,
when I get the picture from network, the picture type is png. I get it and convert the png into jepg. it throws exception.
when run code, the result is below and Exception was thrown :
java.lang.IllegalArgumentException: Composite operation requires the 2 sources to match in number of bands and data type.
     at javax.media.jai.JAI.createNS(JAI.java:1087)
     at javax.media.jai.JAI.create(JAI.java:973)
     at imageprocess.MyImage.ProcessImageAlpha(MyImage.java:254)
     at imageprocess.MyImage.main(MyImage.java:144)
Exception in thread "main" java.lang.IllegalArgumentException: operation "FileStore" requires all source objects to be valid input; a null is supplied.
     at javax.media.jai.JAI.createNS(JAI.java:1087)
     at javax.media.jai.JAI.create(JAI.java:973)
     at imageprocess.MyImage.main(MyImage.java:165)
this is my main code:
public class MyImage {
     public static void main(String[] args) {
          ImagingListener listener = new ImageListener();
          JAI.getDefaultInstance().setImagingListener(listener);
          TileCache tc = JAI.getDefaultInstance().getTileCache();
          tc.setMemoryCapacity(2024 * 2024);
          URL l_url = null;
          JPEGEncodeParam jep = null;
          HttpURLConnection l_connection = null;
          InputStream l_urlStream = null;
          String URLResponse = null;
          SeekableStream fss = null;
          ParameterBlock pb_template = new ParameterBlock();
          int FileLength = 0;
          ParameterBlock pb = null;
          PlanarImage pi = null;
          int ImageWidth = 0;
          int ImageHeight = 0;
          int resolution = 0;
          try {
               String url = "http://static.pieceofnorway.se/img/products/b_TheOne_27.png";//png
               
               url = URLEncode(url);
               System.out.println("url:"+url);
               l_url = new URL(url);
               l_connection = (HttpURLConnection) l_url.openConnection();
               l_connection.setRequestProperty("User-Agent",
                         "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322) ImageCrawler - http://www.pricerunner.se");
               l_connection.setConnectTimeout(20 * 1000); // 20 seconds for default
               l_connection.setReadTimeout(120 * 1000);
               URLResponse = l_connection.getContentType();
               if (URLResponse != null)
                    URLResponse = URLResponse.toLowerCase();
               System.out.println(URLResponse);
               l_urlStream = l_connection.getInputStream();
               FileLength = l_connection.getContentLength();
               System.out.println("File Length:" + FileLength);
//               l_urlStream.close();
          } catch (MalformedURLException e) {
               e.printStackTrace();
          } catch (IOException e) {
               e.printStackTrace();
          } finally {
//               l_connection.disconnect();
               
          }
          fss = SeekableStream.wrapInputStream(l_urlStream, true);
          if (fss == null) {
               System.out.println("fss is null");
          }
          pb = (ParameterBlock) pb_template.clone();
          pb.add(fss);
          pi = JAI.create("stream", pb);
          if (pi == null){
               System.out.println("pi is null");
          }
          ImageWidth = pi.getWidth();
          ImageHeight = pi.getHeight();
          System.out.println("picture width is :"+ImageWidth);
          System.out.println("picture Height is :"+ImageHeight);
          resolution = pi.getHeight()+pi.getWidth();
          System.out.println("picture resolution is :"+resolution);
          System.out.println(pi.getColorModel());
     
          if(pi.getColorModel() instanceof IndexColorModel) {
               
          }else if (pi.getColorModel() instanceof PackedColorModel ||
          pi.getColorModel() instanceof ComponentColorModel ||
          pi.getColorModel() instanceof DirectColorModel ||
          pi.getColorModel() instanceof FloatDoubleColorModel) {
               if (pi.getColorModel().hasAlpha()){
                    pi = ProcessImageAlpha(pi);
                    System.out.println("process pi end!");
               }
          pb.addSource(pi);
          pb.add(getOutPutImageFileName(120));
          pb.add("jpeg");
          pi = JAI.create("filestore", pb, null);
          System.out.println("pic saves!");
          if (jep_template != null){
               jep_template = null;
          }
          if (pb_template != null){
               pb_template = null;
          }
          if (pi != null){
               pi.dispose();
               pi = null;
          }
          if (pb != null){
               pb = null;
          }
          if (fss!=null){
               try {
                    fss.close();
               } catch (IOException e) {
                    
               }
               fss = null;
          }
          if (l_urlStream != null){
               try {
                    l_urlStream.close();
                    l_urlStream = null;
               } catch (IOException e) {
               }
          }
          if (l_connection != null){
               l_connection.disconnect();
               l_connection = null;
          }                         
     }
     
     
     private static String getOutPutImageFileName(int id){
          return "C:/Images/"+id+".jpg";
          }
     private static PlanarImage ProcessImageAlpha(PlanarImage pisrc){
          ParameterBlock pb_template = new ParameterBlock();
          ParameterBlock pb = null;
          PlanarImage pisrcbase = null;
          RenderedImage pisrcalpha = null;
          PlanarImage pidst = null;
          PlanarImage bgImage = null;
          
          Number[] bgbandValues = new Byte[]{ Byte.valueOf((byte) 0xFF), Byte.valueOf((byte) 0xFF), Byte.valueOf((byte) 0xFF)};
          
          try {
               if (!pisrc.getColorModel().hasAlpha()){
                    return pisrc;
               }
               if (pisrc.getNumBands() != 4){
                    return pisrc;
               }
               System.out.println("numbands :"+pisrc.getNumBands());
               System.out.println("has alpha :"+pisrc.getColorModel().hasAlpha());
               pb = (ParameterBlock) pb_template.clone();
               pb.add((float)pisrc.getWidth());
               pb.add((float)pisrc.getHeight());
               pb.add(bgbandValues);
               bgImage = JAI.create("constant", pb, null );
               pb.removeParameters();
               pb = null;
               
               pb = (ParameterBlock) pb_template.clone();
               pb.addSource(pisrc);
               pb.add(new int[]{0,1,2});
               pisrcbase = JAI.create("bandselect", pb, null);
               pb.removeParameters();
               pb = null;
               
               pb = (ParameterBlock) pb_template.clone();
               pb.addSource(pisrc);
               pb.add(new int[]{3});
               pisrcalpha = JAI.create("bandselect", pb, null);
               pb.removeParameters();
               pb = null;
               
               pb = (ParameterBlock) pb_template.clone();
               pb.addSource(pisrcbase);
               pb.addSource(bgImage);
               pb.add(pisrcalpha);
               pb.add(null);
               pb.add(pisrc.getColorModel().isAlphaPremultiplied());
               pb.add(CompositeDescriptor.NO_DESTINATION_ALPHA);
               System.out.println("eeeeeeeeeeeede");
               pidst = JAI.create("composite", pb, null);
               System.out.println("eeeeeeeefeeeee");
               pb.removeParameters();
               pb = null;
               System.out.println("abc");
               return pidst;
          } catch (Exception e) {
               e.printStackTrace();
               System.out.println("exception................");
               return null;
          }
     }

}

class ImageListener implements ImagingListener {
     public boolean errorOccurred(String message, Throwable thrown,
               Object where, boolean isRetryable) throws RuntimeException {
          throw new ImagingException(thrown);
     }
}
Edited by: 976382 on Dec 11, 2012 10:29 PM

Edited by: 976382 on Dec 11, 2012 11:52 PM

Edited by: EJP on 13/12/2012 07:37: added the code tags that you said you added but you didn't.
  • 1. Re: I met a question about  conversion the png into jepg
    EJP Guru
    Currently Being Moderated
    Please reformat that mess with {noformat}
    {noformat} tags so it is as least legible.                                                                                                                                                                                    
  • 2. Re: I met a question about  conversion the png into jepg
    979385 Newbie
    Currently Being Moderated
    I am sorry about it . I have corrected it . thank for you tips. ^-^

    Edited by: 976382 on Dec 11, 2012 10:28 PM
  • 3. Re: I met a question about  conversion the png into jpeg
    StanislavL Pro
    Currently Being Moderated
    What about this approach?
            BufferedImage bi= ImageIO.read(new URL("pathToImage"));
            ByteArrayOutputStream stream=new ByteArrayOutputStream();
            ImageIO.write(bi,"jpg",stream);
  • 4. Re: I met a question about  conversion the png into jpeg
    979385 Newbie
    Currently Being Moderated
    thank for you reply, but the result isn't right . LoL
  • 5. Re: I met a question about  conversion the png into jpeg
    Kayaman Guru
    Currently Being Moderated
    976382 wrote:
    thank for you reply, but the result isn't right .
    What's the result?
    LoL
    What's so funny?

    Also, are you going to fix the formatting in your code or not? Nobody's going to read it when it looks like that.
  • 6. Re: I met a question about  conversion the png into jpeg
    979385 Newbie
    Currently Being Moderated
    Would you teach me how to format the code ? I don't know it . the result show "valid image"
  • 7. Re: I met a question about  conversion the png into jpeg
    gimbal2 Guru
    Currently Being Moderated
    976382 wrote:
    Would you teach me how to format the code ? I don't know it .
    What do you mean!?
    EJP wrote:
    Please reformat that mess with {noformat}
    {noformat} tags so it is as least legible.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
  • 8. Re: I met a question about  conversion the png into jpeg
    979385 Newbie
    Currently Being Moderated
    gimbal2 wrote:
    976382 wrote:
    Would you teach me how to format the code ? I don't know it .
    What do you mean!?
    EJP wrote:
    Please reformat that mess with {noformat}
    {noformat} tags so it is as least legible.
    when the png is pixelBits = 64 , the programme will throw exception below:

    java.lang.IllegalArgumentException: Composite operation requires the 2 sources to match in number of bands and data type.
         at javax.media.jai.JAI.createNS(JAI.java:1087)
         at javax.media.jai.JAI.create(JAI.java:973)
         at imageprocess.MyImage.ProcessImageAlpha(MyImage.java:257)
         at imageprocess.MyImage.main(MyImage.java:144)
  • 9. Re: I met a question about  conversion the png into jpeg
    Maxideon Explorer
    Currently Being Moderated
    For those who stumble onto this thread, the jpeg format for the most part only saves rgb, gray, and cmyk images with 8 bit channels. Though the gray can go up to 16 bits. If you don't pass the ImageWriter such an image, then it's up to the writer to decide what to do. In the original poster's case, it decides to throw an exception complaining about the 16 bit channels.

    Here's a method to save any image as a jpeg. I think I've accounted for all the possibilities, but I have not tested it thoroughly.
    public static void saveAsJPEG(BufferedImage img,
                                  java.io.File dst,
                                  float compressionQuality) throws IOException {
    
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
    
        int colorType = img.getColorModel().getColorSpace().getType();
        if (colorType != ColorSpace.TYPE_RGB &&
            colorType != ColorSpace.TYPE_GRAY &&
            colorType != ColorSpace.TYPE_CMYK) {
            /*Sun's default JPEG image writer will interpret every 3 band
             *BufferedImage as an RGB, and every 4 band BufferedImage as
             *CMYK, even though the BufferedImage may have a completely
             *different ColorSpace (like HLS, YCrCb, or XYZ).  If the
             *BufferedImage is of a different space, then we need to convert
             *it to RGB space to match the JPEG writer's assumption.
             *Furthermore, if an image not of RGB, GRAY, or CMYK space is
             *written then the writer will take an extremely long time to write
             *the image or throw an exception.*/
    
    //            int newType = BufferedImage.TYPE_3BYTE_BGR;
    //            img = colorConvert(img,new BufferedImage(newType,img.getWidth(),
    //                    img.getHeight()));
    
            BufferedImage newImage = new BufferedImage(
                    img.getWidth(),img.getHeight(),
                    BufferedImage.TYPE_3BYTE_BGR);
            new ColorConvertOp(null).filter(img,newImage);
            img = newImage;
        }
    
        ColorModel cm = img.getColorModel();
    
        int alphaBits = cm.hasAlpha()?
                cm.getComponentSize(cm.getNumColorComponents()):0;
        int numColorComponents = cm.getNumColorComponents();
    
    
        if(cm.getPixelSize() - alphaBits > numColorComponents * 8 &&
           !(colorType == ColorSpace.TYPE_GRAY && cm.getPixelSize() == 16)){
            /*If image is more than 8 bits per color, need to normalize 
             *down to 8 bits per color. Exception: 16 bit gray image*/
    
            int[] nBits = cm.getComponentSize();
            for(int i = 0; i < nBits.length; i++) {
                nBits[i] = Math.min(8,nBits);
    }
    if(alphaBits > 8) {alphaBits = 8;}

    ColorModel newCM = new ComponentColorModel(cm.getColorSpace(),
    nBits, alphaBits != 0, false,cm.getTransparency(),
    DataBuffer.TYPE_BYTE);

    int w = img.getWidth();
    int h = img.getHeight();

    WritableRaster srcRast = img.getRaster();
    WritableRaster dstRast = newCM.createCompatibleWritableRaster(w,h);

    int[] unorm = new int[srcRast.getWidth()*nBits.length];
    float[] norm = new float[nBits.length];

    for(int row = 0; row < h; row++) {
    srcRast.getPixels(0,row,w,1,unorm);

    for(int i = 0; i < unorm.length; i += nBits.length) {
    cm.getNormalizedComponents(unorm,i,norm,0);
    newCM.getUnnormalizedComponents(norm,0,unorm,i);
    }
    dstRast.setPixels(0, row, w, 1,unorm);
    }

    img = new BufferedImage(newCM, dstRast,false, null);
    cm = newCM;
    }
    if (cm instanceof IndexColorModel && alphaBits > 0) {
    /*IndexColorModels with transparency do not cooperate well and
    require us to create a new image without the transparency./
    IndexColorModel cmIndex = (IndexColorModel) cm;

    int[] rgbs = new int[cmIndex.getMapSize()];
    cmIndex.getRGBs(rgbs);
    for (int i = 0; i < rgbs.length; i++) {
    rgbs[i] |= 0xFF000000;
    }

    IndexColorModel cmNoAlpha =
    new IndexColorModel(cmIndex.getPixelSize(),
    cmIndex.getMapSize(),
    rgbs, 0, cmIndex.getTransferType(),
    cmIndex.getValidPixels());

    img = new BufferedImage(cmNoAlpha,img.getRaster(),false, null);
    } else if (alphaBits > 0) {
    /*JPEG format does not support transparent colors, so
    *make the image writer not even recognize the alpha channel.  This
    *dosen't work for IndexColorModels which is the reason for
    the 'if' statement above./

    int[] bandsToConsider = new int[cm.getNumColorComponents()];
    int[] nBits = new int[cm.getNumColorComponents()];
    for (int i = 0; i < bandsToConsider.length; i++) {
    bandsToConsider[i] = i;
    nBits[i] = cm.getComponentSize(i);
    }

    param.setSourceBands(bandsToConsider);

    ColorModel tmp = new ComponentColorModel(cm.getColorSpace(),
    nBits, false, false,
    java.awt.Transparency.OPAQUE,
    DataBuffer.TYPE_BYTE);

    param.setDestinationType(new ImageTypeSpecifier(
    tmp,tmp.createCompatibleSampleModel(1, 1)));
    }

    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionQuality(compressionQuality);

    //write out the image
    ImageOutputStream outStream = null;
    try {
    outStream = ImageIO.createImageOutputStream(dst);
    writer.setOutput(outStream);
    writer.write(null,
    new javax.imageio.IIOImage(img, null, null),
    param);
    } finally {
    //clean up
    writer.dispose();
    if(outStream != null)
    outStream.close();
    }
    }

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points