Package com.lightcrafts.mediax.jai.util

Examples of com.lightcrafts.mediax.jai.util.ImagingListener


    /**
     * Stores an image to a file.
     */
    public RenderedImage create(ParameterBlock paramBlock,
                                RenderingHints renderHints) {
        ImagingListener listener = ImageUtil.getImagingListener(renderHints);

        // Retrieve the file path.
        String fileName = (String)paramBlock.getObjectParameter(0);

        // Retrieve the file format preference.
        String format = (String)paramBlock.getObjectParameter(1);

        // TODO: If format is null get format name from file extension.

        // If the format is still null use the default format.
        if(format == null) {
            format = DEFAULT_FORMAT;
        }

        // Retrieve the ImageEncodeParam (which may be null).
        ImageEncodeParam param = null;
        if(paramBlock.getNumParameters() > 2) {
            param = (ImageEncodeParam)paramBlock.getObjectParameter(2);
        }

        // Create a FileOutputStream from the file name.
        OutputStream stream = null;
        try {
            if(param == null) {
                // Use a BufferedOutputStream for greater efficiency
                // since no compression is occurring.
                stream =
                    new BufferedOutputStream(new FileOutputStream(fileName));
            } else {
                // Use SeekableOutputStream to avoid temp cache file
                // in case of compression.
                stream =
                    new SeekableOutputStream(new RandomAccessFile(fileName,
                                                                  "rw"));
            }
        } catch (FileNotFoundException e) {
            String message = JaiI18N.getString("FileLoadRIF0") + fileName;
            listener.errorOccurred(message, e, this, false);
//            e.printStackTrace();
            return null;
        } catch (SecurityException e) {
            String message = JaiI18N.getString("FileStoreRIF0");
            listener.errorOccurred(message, e, this, false);
//            e.printStackTrace();
            return null;
        }

        // Add the operation to the DAG.
View Full Code Here


        return ti;
    }

    void sendExceptionToListener(String message, Exception e) {
        ImagingListener listener = null;
        if (renderingHints != null)
            listener =
                (ImagingListener)renderingHints.get(JAI.KEY_IMAGING_LISTENER);

        if (listener == null)
            listener = JAI.getDefaultInstance().getImagingListener();
        listener.errorOccurred(message, e, this, false);
    }
View Full Code Here

                                      roi,
                                      xStart, yStart,
                                      xPeriod, yPeriod,
                                      numBins, lowValue, highValue);
        } catch (Exception e) {
            ImagingListener listener = ImageUtil.getImagingListener(hints);
            String message = JaiI18N.getString("HistogramRIF0");
            listener.errorOccurred(message, e, this, false);
        }

        return op;
    }
View Full Code Here

      registry.registerServices(null);
      return registry;

  } catch (IOException ioe) {
            ImagingListener listener =
                JAI.getDefaultInstance().getImagingListener();
            String message = JaiI18N.getString("OperationRegistry2");
            listener.errorOccurred(message,
                                   new ImagingException(message, ioe),
                                   OperationRegistry.class, false);
            return null;

//      ioe.printStackTrace();
View Full Code Here

  if (it == null)
      return null;

  FactoryCache fc = getFactoryCache(modeName);
        ImagingListener listener =
            JAI.getDefaultInstance().getImagingListener();
        Exception savedOne = null;

  while (it.hasNext()) {

      Object factory = it.next();
      Object obj;

      try {
    if ((obj = fc.invoke(factory, args)) != null)
        return obj;
                savedOne = null;
      } catch (Exception e) {
                listener.errorOccurred(JaiI18N.getString("OperationRegistry6")+
                                       " \""+descriptorName+"\"",
                                       e, this, false);
                savedOne = e;
//    e.printStackTrace();
      }
View Full Code Here

        Raster raster = null;
        try {
            raster = decoder.decodeAsRaster().createTranslatedChild(tx, ty);
        } catch(Exception e) {

            ImagingListener listener =
                ImageUtil.getImagingListener(renderHints);
            listener.errorOccurred(JaiI18N.getString("IIPResolutionOpImage3"),
                                   new ImagingException(e),
                                   this, false);
/*
            String msg = JaiI18N.getString("IIPResolutionOpImage3")+" "+
                e.getMessage();
View Full Code Here

                RIFRegistry.create(registry, "stream", newParamBlock, renderHints);

            // NB: StreamImage is defined in FileLoadRIF.java.
            return image == null ? null : new StreamImage(image, src);
        } catch (IOException e) {
            ImagingListener listener =
                ImageUtil.getImagingListener(renderHints);
            String message = JaiI18N.getString("URLRIF0");
            listener.errorOccurred(message, e, this, false);
//            e.printStackTrace();
            return null;
        }
    }
View Full Code Here

           (serverMask & SERVER_JPEG_PARTIAL) != SERVER_JPEG_PARTIAL &&
           (serverMask & SERVER_FPX_PARTIAL) != SERVER_FPX_PARTIAL) {
            return null;
        }

        ImagingListener listener = ImageUtil.getImagingListener(renderContext);

        // Set JPEG and full server flags.
        boolean isJPEG = false;
        boolean isFull = false;
        if((serverMask & SERVER_JPEG_FULL) == SERVER_JPEG_FULL) {
            isJPEG = isFull = true;
        } else if((serverMask & SERVER_FPX_FULL) == SERVER_FPX_FULL) {
            isJPEG = false;
            isFull = true;
        } else if((serverMask & SERVER_JPEG_PARTIAL) == SERVER_JPEG_PARTIAL) {
            isJPEG = true;
            isFull = false;
        }

        // Create a StringBuffer for the composed image command URL.
        StringBuffer buf =
            new StringBuffer((String)paramBlock.getObjectParameter(0));
        //TODO: subImages (how?)

        // Filtering.
        if((opMask & MASK_FILTER) != 0) {
            buf.append("&FTR="+paramBlock.getFloatParameter(2));
        }

        // Color-twist.
        if((opMask & MASK_COLOR_TWIST) != 0) {
            buf.append("&CTW=");
            float[] ctw = (float[])paramBlock.getObjectParameter(3);
            for(int i = 0; i < ctw.length; i++) {
                buf.append(ctw[i]);
                if(i != ctw.length-1) {
                    buf.append(",");
                }
            }
        }

        // Contrast.
        if((opMask & MASK_CONTRAST) != 0) {
            buf.append("&CNT="+paramBlock.getFloatParameter(4));
        }

        // Source rectangle of interest.
        if((opMask & MASK_ROI_SOURCE) != 0) {
            Rectangle2D roi =
                (Rectangle2D)paramBlock.getObjectParameter(5);
            buf.append("&ROI="+roi.getX()+","+ roi.getY()+","+
                       roi.getWidth()+","+roi.getHeight());
        }

        // If full support for the CVT command is available, decompose the
        // AffineTransform specifying the transformation from renderable to
        // rendered coordinates into a translation, a pure scale, and the
        // residual transformation. The residual transformation may then be
        // concatenated with the server-side affine transform (after
        // inversion), the pure scale may be effected by specifying the WID
        // and HEI composed image command modifiers, and the translation as
        // a subsequent operation. If the WID and HEI modifiers are not
        // available, i.e., the server support is partial, this becomes
        // more problematic. Fortunately no such servers are known to exist.

        // Initialize the post-processing transform to the identity.
        AffineTransform postTransform = new AffineTransform();

        // Retrieve (a clone of) the renderable-to-rendered mapping.
        AffineTransform at =
            (AffineTransform)renderContext.getTransform().clone();

        // If the translation is non-zero set the post-transform.
        if(at.getTranslateX() != 0.0 || at.getTranslateY() != 0.0) {
            postTransform.setToTranslation(at.getTranslateX(),
                                           at.getTranslateY());
            double[] m = new double[6];
            at.getMatrix(m);
            at.setTransform(m[0], m[1], m[2], m[3], 0.0, 0.0);
        }

        // Determine the renderable destination region of interest.
        Rectangle2D rgn = null;
        if((opMask & MASK_ROI_DESTINATION) != 0) {
            rgn = (Rectangle2D)paramBlock.getObjectParameter(8);
        } else {
            float aspectRatio = 1.0F;
            if((opMask & MASK_ASPECT_RATIO) != 0) {
                aspectRatio = paramBlock.getFloatParameter(7);
            } else {
                aspectRatio =
                    ((Float)(lowRes.getProperty("aspect-ratio"))).floatValue();
            }
            rgn = new Rectangle2D.Float(0.0F, 0.0F, aspectRatio, 1.0F);
        }

        // Apply the renderable-to-rendered mapping to the renderable
        // destination region of interest.
        Rectangle dstROI = at.createTransformedShape(rgn).getBounds();

        // Calculate the pure scale portion of the
        // renderable-to-rendered mapping.
        AffineTransform scale =
            AffineTransform.getScaleInstance(dstROI.getWidth()/
                                             rgn.getWidth(),
                                             dstROI.getHeight()/
                                             rgn.getHeight());

        // Determine the residual mapping.
        try {
            at.preConcatenate(scale.createInverse());
        } catch(Exception e) {
            String message = JaiI18N.getString("IIPCRIF6");
            listener.errorOccurred(message,
                                   new ImagingException(message, e),
                                   this, false);
//            throw new RuntimeException(JaiI18N.getString("IIPCRIF6"));
        }

        // Compose the inverse residual mapping with the renderable
        // transform.
        AffineTransform afn =
            (AffineTransform)paramBlock.getObjectParameter(6);
        try {
            afn.preConcatenate(at.createInverse());
        } catch(Exception e) {
            String message = JaiI18N.getString("IIPCRIF6");
            listener.errorOccurred(message,
                                   new ImagingException(message, e),
                                   this, false);
//            throw new RuntimeException(JaiI18N.getString("IIPCRIF6"));
        }

        if(isFull) {
            // Append the WID and HEI composed image command modifiers using
            // the dimensions of the rendered destination region of interest.
            buf.append("&WID="+dstROI.width+"&HEI="+dstROI.height);
            /* XXX Begin suppressed section.
        } else if((opMask & MASK_TRANSFORM) != 0) {
            Point2D[] dstPts =
                new Point2D[] {new Point2D.Double(rgn.getMinX(),
                                                  rgn.getMinY()),
                                   new Point2D.Double(rgn.getMaxX(),
                                                      rgn.getMinY()),
                                   new Point2D.Double(rgn.getMinX(),
                                                      rgn.getMaxY())};
            Point2D[] srcPts = new Point2D[3];
            afn.transform(dstPts, 0, srcPts, 0, 3);

            double LLeft = srcPts[0].distance(srcPts[2]);
            double LTop = srcPts[0].distance(srcPts[1]);

            int[] maxSize = (int[])lowRes.getProperty("max-size");

            double H = maxSize[1]*LLeft;
            double W = maxSize[1]*LTop;

            double m = Math.max(H, W*(double)maxSize[1]/(double)maxSize[0]);

            int Hp = (int)(m + 0.5);
            int Wp = (int)(m*(double)maxSize[0]/(double)maxSize[1] + 0.5);
            System.out.println("Estimated dimensions = "+Wp+" x "+Hp);

            AffineTransform scl =
                AffineTransform.getScaleInstance(dstROI.getWidth()/Wp,
                                                 dstROI.getHeight()/Hp);
            System.out.println("scl = "+scl);
            afn.preConcatenate(scl);
            End suppressed section. XXX */
        }


        // Append the affine tranform composed image command.
        double[] matrix = new double[6];
        afn.getMatrix(matrix);
        buf.append("&AFN="+
                   matrix[0]+","+matrix[2]+",0,"+matrix[4]+","+
                   matrix[1]+","+matrix[3]+",0,"+matrix[5]+
                   ",0,0,1,0,0,0,0,1");

        // Destination aspect ratio.
        if((opMask & MASK_ASPECT_RATIO) != 0) {
            buf.append("&RAR="+paramBlock.getFloatParameter(7));
        }

        // Destination rectangle of interest.
        if((opMask & MASK_ROI_DESTINATION) != 0) {
            Rectangle2D dstRGN =
                (Rectangle2D)paramBlock.getObjectParameter(8);
            buf.append("&RGN="+dstRGN.getX()+","+ dstRGN.getY()+","+
                       dstRGN.getWidth()+","+dstRGN.getHeight());
        }

        // Rotation and mirroring.
        if(isFull) {
            if((opMask & MASK_ROTATION) != 0 ||
               (opMask & MASK_MIRROR_AXIS) != 0) {
                buf.append("&RFM="+paramBlock.getIntParameter(9));
                if((opMask & MASK_MIRROR_AXIS) != 0) {
                    String axis = (String)paramBlock.getObjectParameter(10);
                    if(axis.equalsIgnoreCase("x")) {
                        buf.append(",0");
                    } else {
                        buf.append(",90");
                    }
                }
            }
        }

        // ICC profile.
        if((opMask & MASK_ICC_PROFILE) != 0) {
            // According to the IIP specification this is not supported
            // over HTTP connections and that is all that is available from
            // the vendors right now, i.e., no socket connections are
            // available (includes LivePicture and TrueSpectra).
        }

        // JPEG quality and compression group index.
        if(isJPEG) {
            if((opMask & MASK_JPEG_QUALITY) != 0) {
                buf.append("&QLT="+paramBlock.getIntParameter(12));
            }

            if((opMask & MASK_JPEG_TABLE) != 0) {
                buf.append("&CIN="+paramBlock.getIntParameter(13));
            }
        }

        // Set the format string.
        String format = isJPEG ? "JPEG" : "FPX";

        // Append the CVT command.
        buf.append("&CVT="+format);

        // Create a URL with the CVT string, open a stream from it, and
        // decode the image using the appropriate decoder.
        InputStream stream = null;
        RenderedImage rendering = null;
        try {
            URL url = new URL(buf.toString());
            stream = url.openStream();
            MemoryCacheSeekableStream sStream =
                new MemoryCacheSeekableStream(stream);
            rendering = JAI.create(format, sStream);
        } catch(Exception e) {
            String message =
                JaiI18N.getString("IIPCRIF7") + " " + buf.toString();
            listener.errorOccurred(message,
                                   new ImagingException(message, e),
                                   this, false);
//            throw new RuntimeException(e.getClass()+" "+e.getMessage());
        }

View Full Code Here

                                     RenderedImage lowRes) {
        // Cache RenderContext components.
        AffineTransform at = renderContext.getTransform();
        RenderingHints hints = renderContext.getRenderingHints();

        ImagingListener listener = ImageUtil.getImagingListener(renderContext);

        // Obtain the number of levels and the size of the largest one.
        int[] maxSize = (int[])lowRes.getProperty("max-size");
        int maxWidth = maxSize[0];
        int maxHeight = maxSize[1];
        int numLevels =
            ((Integer)lowRes.getProperty("resolution-number")).intValue();

        // Calculate the aspect ratios.
        float aspectRatioSource = (float)maxWidth/(float)maxHeight;
        float aspectRatio = (opMask & MASK_ASPECT_RATIO) != 0 ?
            paramBlock.getFloatParameter(7) : aspectRatioSource;

        // Determine the bounds of the destination image.
        Rectangle2D bounds2D = new Rectangle2D.Float(0.0F, 0.0F,
                                                     aspectRatio, 1.0F);

        // Determine the dimensions of the rendered destination image.
        int width;
        int height;
        if(at.isIdentity()) { // Default rendering.
            AffineTransform afn =
                (AffineTransform)paramBlock.getObjectParameter(6);
            Rectangle2D bounds =
                afn.createTransformedShape(bounds2D).getBounds2D();
            double H = maxHeight*bounds.getHeight();
            double W = maxHeight*bounds.getWidth();
            double m = Math.max(H, W/aspectRatioSource);
            height = (int)(m + 0.5);
            width = (int)(aspectRatioSource*m + 0.5);
            at = AffineTransform.getScaleInstance(width, height);
            renderContext = (RenderContext)renderContext.clone();
            renderContext.setTransform(at);
        } else {
            Rectangle bounds = at.createTransformedShape(bounds2D).getBounds();
            width = bounds.width;
            height = bounds.height;
        }

        // Determine which resolution level of the IIP image to request.
        int res = numLevels - 1;
        int hRes = maxHeight;
        while(res > 0) {
            hRes = (int)((hRes + 1.0F)/2.0F); // get the next height
            if(hRes < height) { // stop if the next height is too small
                break;
            }
            res--;
        }

        // Create a RenderableImage from the selected resolution level.
        int[] subImageArray = (int[])paramBlock.getObjectParameter(1);
        int subImage = subImageArray.length < res + 1 ? 0 : subImageArray[res];
        if(subImage < 0) {
            subImage = 0;
        }
        ParameterBlock pb = new ParameterBlock();
        pb.add(paramBlock.getObjectParameter(0)).add(res).add(subImage);
        RenderedImage iipRes = JAI.create("iipresolution", pb);
        Vector sources = new Vector(1);
        sources.add(iipRes);
        RenderableImage ri =
            new MultiResolutionRenderableImage(sources, 0.0F, 0.0F,
                                               1.0F);

        // Filtering.
        if((opMask & MASK_FILTER) != 0) {
            float filter = paramBlock.getFloatParameter(2);
            pb = (new ParameterBlock()).addSource(ri).add(filter);
            ri = new RenderableImageOp(new FilterCRIF(), pb);
        }

        // Color-twist.
        // Cache the original number of bands in case the number of bands
        // changes due to addition of chroma and/or alpha channels in the
        // color-twist procedure.
  int nBands = iipRes.getSampleModel().getNumBands();
        if((opMask & MASK_COLOR_TWIST) != 0) {
      double[][] ctw = getColorTwistMatrix(iipRes.getColorModel(),
             paramBlock);
            pb = (new ParameterBlock()).addSource(ri).add(ctw);
            ri = JAI.createRenderable("bandcombine", pb);
      nBands = ctw.length;
        }

        // Contrast.
        if((opMask & MASK_CONTRAST) != 0) {
            int csType = iipRes.getColorModel().getColorSpace().getType();
            boolean isPYCC =
                csType != ColorSpace.TYPE_GRAY &&
                csType != ColorSpace.TYPE_RGB;

            if(isPYCC) {
                double[][] matrix;
                if(nBands == 3) { // PYCC
                    matrix = composeMatrices(YCC_TO_RGB, YCC_TO_RGB_CONST);
                } else { // PYCC-A
                    matrix = composeMatrices(YCCA_TO_RGBA, YCCA_TO_RGBA_CONST);
                }
                pb = (new ParameterBlock()).addSource(ri).add(matrix);
                ri = JAI.createRenderable("bandcombine", pb);
            }

            float contrast = paramBlock.getFloatParameter(4);
            LookupTableJAI lut = createContrastLUT(contrast, nBands);

            pb = (new ParameterBlock()).addSource(ri).add(lut);
            ri = JAI.createRenderable("lookup", pb);

            if(isPYCC) {
                double[][] matrix;
                if(nBands == 3) { // PYCC
                    matrix = composeMatrices(RGB_TO_YCC, RGB_TO_YCC_CONST);
                } else { // PYCC-A
                    matrix = composeMatrices(RGBA_TO_YCCA, RGBA_TO_YCCA_CONST);
                }
                pb = (new ParameterBlock()).addSource(ri).add(matrix);
                ri = JAI.createRenderable("bandcombine", pb);
            }
        }

        // Source rectangle of interest.
        if((opMask & MASK_ROI_SOURCE) != 0) {
            // Get the source rectangle of interest.
            Rectangle2D rect = (Rectangle2D)paramBlock.getObjectParameter(5);

            // Check for intersection with source bounds.
            if(!rect.intersects(0.0, 0.0, aspectRatioSource, 1.0)) {
                throw new RuntimeException(JaiI18N.getString("IIPCRIF5"));
            }

            // Create the source rectangle.
            Rectangle2D rectS = new Rectangle2D.Float(0.0F, 0.0F,
                                                      aspectRatioSource, 1.0F);

            // Crop out the desired region.
            if(!rect.equals(rectS)) {
                // Clip to the source bounds.
                rect = rect.createIntersection(rectS);

                // Crop to the clipped rectangle of interest.
                pb = (new ParameterBlock()).addSource(ri);
                pb.add((float)rect.getMinX()).add((float)rect.getMinY());
                pb.add((float)rect.getWidth()).add((float)rect.getHeight());
                ri = JAI.createRenderable("crop", pb);

                /* XXX
                // Embed the cropped image in an image the size of the source.
                pb = (new ParameterBlock()).addSource(ri);
                pb.add((float)rectS.getMinX()).add((float)rectS.getMinY());
                pb.add((float)rectS.getWidth()).add((float)rectS.getHeight());
                ri = JAI.createRenderable("crop", pb);
                */
            }
        }

        // Spatial orientation.
        if((opMask & MASK_TRANSFORM) != 0) {
            AffineTransform afn =
                (AffineTransform)paramBlock.getObjectParameter(6);
            try {
                // The transform parameter is a backward mapping so invert it.
                afn = afn.createInverse();
            } catch(java.awt.geom.NoninvertibleTransformException e) {
                // This should never happen due to descriptor check.
                listener.errorOccurred(JaiI18N.getString("AffineNotInvertible"),
                                       e, this, false);

            }
            pb = (new ParameterBlock()).addSource(ri).add(afn);
            if(hints != null && hints.containsKey(JAI.KEY_INTERPOLATION)) {
View Full Code Here

    public RenderedImage create(RenderContext renderContext,
                                ParameterBlock paramBlock) {
        // Get the operation mask.
        int opMask = getOperationMask(paramBlock);

        ImagingListener listener = ImageUtil.getImagingListener(renderContext);

        // Get the lowest resolution level of the IIP image for property use.
        ParameterBlock pb = new ParameterBlock();
        int[] subImageArray = (int[])paramBlock.getObjectParameter(1);
        pb.add(paramBlock.getObjectParameter(0)).add(0).add(subImageArray[0]);
        RenderedImage lowRes = JAI.create("iipresolution", pb);

        // Get the server capability mask.
        int serverMask =
            getServerCapabilityMask((String)paramBlock.getObjectParameter(0),
                                    lowRes);

        RenderedImage rendering = null;

        // Select the processing path based on the server's capabilities.
        if((serverMask & SERVER_JPEG_FULL) == SERVER_JPEG_FULL ||
           (serverMask & SERVER_FPX_FULL) == SERVER_FPX_FULL ||
           (serverMask & SERVER_JPEG_PARTIAL) == SERVER_JPEG_PARTIAL ||
           (serverMask & SERVER_FPX_PARTIAL) == SERVER_FPX_PARTIAL) {
            // All (FULL) or most (PARTIAL) ops on server
            rendering = serverProc(serverMask,
                                   renderContext, paramBlock, opMask, lowRes);
        } else {
            // All ops on client
            rendering = clientProc(renderContext, paramBlock, opMask, lowRes);

            // Do special processing if source rectangle of interest given.
            // The following approach works but is rather slow.
            if((opMask & MASK_ROI_SOURCE) != 0) {
                // Retrieve the source rectangle of interest.
                Rectangle2D rgn =
                    (Rectangle2D)paramBlock.getObjectParameter(5);

                // Retrieve a clone of the renderable transform.
                AffineTransform at = (AffineTransform)
                    ((AffineTransform)(paramBlock.getObjectParameter(6))).clone();

                // If the transform is not the identity, invert it.
                if(!at.isIdentity()) {
                    try {
                    at = at.createInverse();
                    } catch(Exception e) {
                        String message = JaiI18N.getString("IIPCRIF6");
                        listener.errorOccurred(message,
                                               new ImagingException(message, e),
                                               this, false);

//                        throw new RuntimeException(JaiI18N.getString("IIPCRIF6"));
                    }
View Full Code Here

TOP

Related Classes of com.lightcrafts.mediax.jai.util.ImagingListener

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.