Java Code Examples for javax.media.jai.JAI#create()

The following examples show how to use javax.media.jai.JAI#create() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FolderImageStorage.java    From pdfxtk with Apache License 2.0 6 votes vote down vote up
/** @param id unique id given to the image 
  */
 public RenderedOp getImage(String id) 
   throws ImageStorageException
 {
   try { 
     File f = new File(folder+"sign_"+id+".tif");
     FileInputStream is = new FileInputStream(f);
     byte[] b = new byte[(new Long(f.length())).intValue()];
     is.read(b);
     ByteArraySeekableStream stream = new ByteArraySeekableStream(b);
     RenderedOp img = JAI.create("stream",stream);
     is.close();
     return img;    
  }
   catch(FileNotFoundException e1) {
     throw new ImageStorageException
("File "+folder+"sign_"+id+".tif not found");
   }
   catch(IOException e2) {
     throw new ImageStorageException
("Class FolderImageStorage : IOException throwed : msg : "+e2.getMessage());
   }
 }
 
Example 2
Source File: JaiLoader.java    From libreveris with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Try to load an image, using JAI.
 * This seems limited to a single image, thus no id parameter is to be
 * provided.
 *
 * @param imgFile the input file
 * @return a map of one image, or null if failed to load
 */
public static SortedMap<Integer, RenderedImage> loadJAI (File imgFile)
{
    RenderedImage image = JAI.create("fileload", imgFile.getPath());

    try {
        if ((image.getWidth() > 0) && (image.getHeight() > 0)) {
            SortedMap<Integer, RenderedImage> images = new TreeMap<>();
            images.put(1, image);

            return images;
        }
    } catch (Exception ex) {
        logger.debug(ex.getMessage());
    }

    return null;
}
 
Example 3
Source File: QuicklookOlciDescriptor.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Create the Render Operator to compute Olci quicklook.
 *
 * <p>Creates a <code>ParameterBlockJAI</code> from all
 * supplied arguments except <code>hints</code> and invokes
 * {@link JAI#create(String,ParameterBlock,RenderingHints)}.
 *
 * @see JAI
 * @see ParameterBlockJAI
 * @see RenderedOp
 *
 * @param source_red the RenderedImage red source.
 * @param source_green the RenderedImage green source.
 * @param source_blue the RenderedImage blue source.
 * @param detectors list of detector indexes.
 * @param sza list of solar zenith angles.
 * @param solar_flux list of solar flux.
 * @param pixels_correction per bands scale/offset pixels correction
 * @param bands list of bands in the order they are provided.
 * @param bands_coefficients list of global coefficient per bands.
 * @return The <code>RenderedOp</code> destination.
 * @throws IllegalArgumentException if sources is null.
 * @throws IllegalArgumentException if a source is null.
 */
public static RenderedOp create(short[][] detectors, double[][]sza, 
   float[][]solar_flux, PixelCorrection[]pixels_correction, int[]bands,
   int[]bands_coefficients, RenderingHints hints, RenderedImage... sources)
{
   ParameterBlockJAI pb =
      new ParameterBlockJAI(OPERATION_NAME,
            RenderedRegistryMode.MODE_NAME);

   int numSources = sources.length;
   // Check on the source number
   if (numSources <= 0)
   {
      throw new IllegalArgumentException("No resources are present");
   }
   
   // Setting of all the sources
   for (int index = 0; index < numSources; index++)
   {
      RenderedImage source = sources[index];
      if (source == null)
      {
         throw new IllegalArgumentException("This resource is null");
      }
      pb.setSource(source, index);
   }
   /*To Be remove */
   pb.setParameter(paramNames[0], detectors);
   pb.setParameter(paramNames[1], sza);
   pb.setParameter(paramNames[2], solar_flux);
   pb.setParameter(paramNames[3], pixels_correction);
   pb.setParameter(paramNames[4], bands);
   pb.setParameter(paramNames[5], bands_coefficients);
   
   return JAI.create(OPERATION_NAME, pb, hints);
}
 
Example 4
Source File: ImageStorageTest.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
/** construct an ImageStorage based on a folder
    @param folder name of the folder used to put and get images 
*/
public ImageStorageTest(String imgName, String folderName) 
  throws ImageStorageException {

  ImageStorage imgStore = 
    new FolderImageStorage(folderName);
  RenderedOp img = JAI.create("fileload",imgName);
  imgStore.storeImage(img,"toto.tif+100+100+100+100");
  img = imgStore.getImage("toto.tif+100+100+100+100");
  imgStore.storeImage(img,"tutu.tif+10+10+50+50");
}
 
Example 5
Source File: Picture.java    From libreveris with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static PlanarImage RGBAToGray (PlanarImage image)
{
    logger.info("Discarding alpha band ...");

    PlanarImage pi = JAI.create("bandselect", image, new int[]{0, 1, 2});

    return RGBToGray(pi);
}
 
Example 6
Source File: TestWarp.java    From libreveris with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new TestWarp object.
 */
public TestWarp (String path)
{
    srcImage = JAI.create("fileload", new ParameterBlock().add(path), null);
    //        srcImage = PictureLoader.loadImages(new File(path), null)
    //                                .get(1);
    //        srcImage = buildPattern(20, 10, 50, 50);
    dimension = new Dimension(srcImage.getWidth(), srcImage.getHeight());
    setPreferredSize(dimension);

    //        float[]        xCoeffs = new float[] { 0f, 1.25f, 0.04f };
    //        float[]        yCoeffs = new float[] { 0f, -0.02f, 1.5f };
    //        Warp           warp = new WarpAffine(xCoeffs, yCoeffs);
    //
    int            xStep = 500;
    int            xNumCells = 2;
    int            yStep = 500;
    int            yNumCells = 1;
    float[]        warpPositions = new float[] {
                                       -100f, 0f, 500f, 100f, 1000f, 0f, // top line
    0f, 500f, 500f, 500f, 1000f, 500f
                                   }; // bot line
    Warp           warp = new WarpGrid(
        0,
        xStep,
        xNumCells,
        0,
        yStep,
        yNumCells,
        warpPositions);
    ParameterBlock pb = new ParameterBlock();
    pb.addSource(invert(srcImage));
    pb.add(warp);
    pb.add(new InterpolationBilinear());
    dstImage = invert(JAI.create("warp", pb));
    ((PlanarImage) dstImage).getTiles();
}
 
Example 7
Source File: FeatureUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Helper function to run the Vectorize operation with given parameters and
 * retrieve the vectors.
 * 
 * @param src the source {@link GridCoverage2D}.
 * @param args a {@code Map} of parameter names and values or <code>null</code>.
 * 
 * @return the generated vectors as JTS Polygons
 */
@SuppressWarnings("unchecked")
public static Collection<Polygon> doVectorize( GridCoverage2D src, Map<String, Object> args ) {
    if (args == null) {
        args = new HashMap<String, Object>();
    }

    ParameterBlockJAI pb = new ParameterBlockJAI("Vectorize");
    pb.setSource("source0", src.getRenderedImage());

    // Set any parameters that were passed in
    for( Entry<String, Object> e : args.entrySet() ) {
        pb.setParameter(e.getKey(), e.getValue());
    }

    // Get the desintation image: this is the unmodified source image data
    // plus a property for the generated vectors
    RenderedOp dest = JAI.create("Vectorize", pb);

    // Get the vectors
    Collection<Polygon> polygons = (Collection<Polygon>) dest.getProperty(VectorizeDescriptor.VECTOR_PROPERTY_NAME);

    RegionMap regionParams = CoverageUtilities.getRegionParamsFromGridCoverage(src);
    double xRes = regionParams.getXres();
    double yRes = regionParams.getYres();
    final AffineTransform mt2D = (AffineTransform) src.getGridGeometry().getGridToCRS2D(PixelOrientation.CENTER);
    final AffineTransformation jtsTransformation = new AffineTransformation(mt2D.getScaleX(), mt2D.getShearX(),
            mt2D.getTranslateX() - xRes / 2.0, mt2D.getShearY(), mt2D.getScaleY(), mt2D.getTranslateY() + yRes / 2.0);
    for( Polygon polygon : polygons ) {
        polygon.apply(jtsTransformation);
    }
    return polygons;
}
 
Example 8
Source File: ImageViewer.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
public static void main(String[] arg) {
  if (arg.length != 1) {
    System.err.println("Usage: iiuf.jai.ImageViewer <image>");
    System.exit(0);
  }
  new ImageViewer(JAI.create("fileload", arg[0]));
}
 
Example 9
Source File: ExportRgbWithLayer.java    From snap-examples with GNU General Public License v3.0 5 votes vote down vote up
public static void quicklookRGBwOverlay(Product product, File rgbFile, String[] RGBbandNames, String vectorName) throws IOException {
/* Create RGB image */
    Band[] bands = new Band[3];

    for (int k = 0; k < RGBbandNames.length; k++){
        bands[k] = product.getBand(RGBbandNames[k]);
    }

    ImageInfo information = ProductUtils.createImageInfo(bands, true, ProgressMonitor.NULL);
    RenderedImage renderedRGB = ImageManager.getInstance().createColoredBandImage(bands, information, 0);

/* Create image layers*/
    CollectionLayer collectionLayer = new CollectionLayer();
    LayerContext ctx = new MyLayerContext(product, collectionLayer);
    SceneTransformProvider provider = bands[0];
    MultiLevelModel multiLevelModel = bands[0].getMultiLevelModel();

    // RGB
    ImageLayer RGBLayer = new ImageLayer(renderedRGB, bands[0].getImageToModelTransform(), 1);

    // Vector
    VectorDataNode vectorDataNode = product.getVectorDataGroup().get(vectorName);
    VectorDataLayer vectorDataLayer = new VectorDataLayer(ctx, vectorDataNode, provider );

/* Create the complete image by overlaying */
    collectionLayer.getChildren().add(vectorDataLayer);
    collectionLayer.getChildren().add(RGBLayer);

    BufferedImage buffered = new BufferedImage(renderedRGB.getWidth(), renderedRGB.getHeight(), BufferedImage.TYPE_INT_ARGB);
    BufferedImageRendering rendering = createRendering(buffered, multiLevelModel);
    collectionLayer.render(rendering);

    JAI.create("filestore", rendering.getImage(), rgbFile.toString(), "PNG");

}
 
Example 10
Source File: ImageUtils.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
private BufferedImage privateReadFromFile(final File file, final boolean forOpenGL) throws IOException {
	// DEBUG.OUT("READING " + file.getName());
	BufferedImage result = getNoImage();
	if (file == null) { return result; }
	final String name = file.getName();
	String ext = null;
	if (name.contains(".")) {
		ext = name.substring(file.getName().lastIndexOf('.'));
	}
	if (tiffExt.contains(ext)) {
		try (FileSeekableStream stream = new FileSeekableStream(file.getAbsolutePath())) {
			/**
			 * AD TODO : decodeParam is not used ...
			 */
			// final TIFFDecodeParam decodeParam = new TIFFDecodeParam();
			// decodeParam.setDecodePaletteAsShorts(true);
			final ParameterBlock params = new ParameterBlock();
			params.add(stream);
			final RenderedOp image1 = JAI.create("tiff", params);
			return image1.getAsBufferedImage();
		}
	} else if (gifExt.contains(ext)) {
		final GifDecoder d = new GifDecoder();
		d.read(new FileInputStream(file.getAbsolutePath()));
		return d.getImage();
	}

	try {
		result = forOpenGL ? ImageIO.read(file) : toCompatibleImage(ImageIO.read(file));
	} catch (final Exception e) {
		return getNoImage();
	}
	return result;
}
 
Example 11
Source File: ProcessingUtils.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
public static RenderedImage resizeImage(RenderedImage image, int width, int height)
      throws InconsistentImageScale
{
   RenderedImage resizedImage=image;
   // Computes ratio and scale
   float scale=getScale(image.getWidth(),image.getHeight(),width,height);
   
   // Processing resize process
   ParameterBlock pb = new ParameterBlock();
   // The source image
   pb.addSource(resizedImage);
   // The xScale
   pb.add(scale);
   // The yScale
   pb.add(scale);
   // The x translation
   pb.add(0.0F);
   // The y translation
   pb.add(0.0F);
   // The interpolation
   pb.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC));
   resizedImage = JAI.create("scale", pb, null);
   
   LOGGER.debug("Image resized to : " + resizedImage.getWidth() + "x"
      + resizedImage.getHeight());
   
   return resizedImage;
}
 
Example 12
Source File: S3HistogramEqualizerDescriptor.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Render the Equalization of pixels of the image.
 *
 * <p>Creates a <code>ParameterBlockJAI</code> from all
 * supplied arguments except <code>hints</code> and invokes
 * {@link JAI#create(String,ParameterBlock,RenderingHints)}.
 *
 * @see JAI
 * @see ParameterBlockJAI
 * @see RenderedOp
 *
 * @param hints processing image hints.
 * @param sources list of sources.
 * @return The <code>RenderedOp</code> destination.
 * @throws IllegalArgumentException if <code>sources</code> is <code>null</code>.
 * @throws IllegalArgumentException if a <code>source</code> is <code>null</code>.
 */
public static RenderedOp create(RenderingHints hints, RenderedImage... sources)
{
   ParameterBlockJAI pb =
      new ParameterBlockJAI(OPERATION_NAME,
            RenderedRegistryMode.MODE_NAME);

   int numSources = sources.length;
   // Check on the source number
   if (numSources <= 0)
   {
      throw new IllegalArgumentException("No resources are present");
   }
   
   // Setting of all the sources
   for (int index = 0; index < numSources; index++)
   {
      RenderedImage source = sources[index];
      if (source == null)
      {
         throw new IllegalArgumentException("This resource is null");
      }
      pb.setSource(source, index);
   }
   
   return JAI.create(OPERATION_NAME, pb, hints);
}
 
Example 13
Source File: JAIConverter.java    From mdict-java with GNU General Public License v3.0 5 votes vote down vote up
@Override
public byte[] terminateTiff(InputStream data) throws Exception {
	RenderedOp src = JAI.create("Stream", SeekableStream.wrapInputStream(data, true));
	PNGEncodeParam.Palette pngEncodeParam = new PNGEncodeParam.Palette();
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	ImageEncoder enc = ImageCodec.createImageEncoder("PNG", bos, pngEncodeParam);
	enc.encode(src);
	return bos.toByteArray();
}
 
Example 14
Source File: QuicklookSlstrDescriptor.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Create the Render Operator to compute SLSTR quicklook.
 *
 * <p>Creates a <code>ParameterBlockJAI</code> from all
 * supplied arguments except <code>hints</code> and invokes
 * {@link JAI#create(String,ParameterBlock,RenderingHints)}.
 *
 * @see JAI
 * @see ParameterBlockJAI
 * @see RenderedOp
 *
 * @return The <code>RenderedOp</code> destination.
 * @throws IllegalArgumentException if sources is null.
 * @throws IllegalArgumentException if a source is null.
 */
public static RenderedOp create(PixelCorrection[]pixels_correction,
   RenderingHints hints, RenderedImage... sources)
{
   ParameterBlockJAI pb =
      new ParameterBlockJAI(OPERATION_NAME,
            RenderedRegistryMode.MODE_NAME);

   int numSources = sources.length;
   // Check on the source number
   if (numSources <= 0)
   {
      throw new IllegalArgumentException("No resources are present");
   }
   
   // Setting of all the sources
   for (int index = 0; index < numSources; index++)
   {
      RenderedImage source = sources[index];
      if (source == null)
      {
         throw new IllegalArgumentException("This resource is null");
      }
      pb.setSource(source, index);
      pb.setParameter(paramNames[0], pixels_correction);
   }
   return JAI.create(OPERATION_NAME, pb, hints);
}
 
Example 15
Source File: ImageCompareUtil.java    From qaf with MIT License 5 votes vote down vote up
private RenderedImage rescale(RenderedImage i) {
	float scaleW = ((float) baseSize) / i.getWidth();
	float scaleH = ((float) baseSize) / i.getHeight();
	// Scales the original image
	ParameterBlock pb = new ParameterBlock();
	pb.addSource(i);
	pb.add(scaleW);
	pb.add(scaleH);
	pb.add(0.0F);
	pb.add(0.0F);
	pb.add(new InterpolationNearest());
	// Creates a new, scaled image and uses it on the DisplayJAI component
	return JAI.create("scale", pb);
}
 
Example 16
Source File: TestImage3.java    From libreveris with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static PlanarImage grayToGray256 (PlanarImage image)
    {
        System.out.println("Converting gray image to gray-256 ...");

        ColorSpace colorSpace = ColorSpace.getInstance
            (java.awt.color.ColorSpace.CS_GRAY);

//        int[] bits = new int[]{8};
//        int opaque = Transparency.OPAQUE;
//        int dataType = DataBuffer.TYPE_BYTE;
//        ColorModel colorModel = new ComponentColorModel
//            (colorSpace, bits, false, false, opaque, dataType);

        return JAI.create("colorConvert", image, colorSpace, null);
    }
 
Example 17
Source File: ClassImageRenderer.java    From orbit-image-analysis with GNU General Public License v3.0 5 votes vote down vote up
public void saveToDisk(TiledImage ti, String fn) throws IOException {
    BufferedImage buffImg = new BufferedImage(ti.getWidth(), ti.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics g2d = buffImg.getGraphics();
    g2d.drawImage(ti.getAsBufferedImage(), 0, 0, null);
    buffImg.flush();

    JPEGEncodeParam jpgParam = new JPEGEncodeParam();
    jpgParam.setQuality(0.85f);
    JAI.create("filestore", buffImg, fn, "JPEG", jpgParam);
}
 
Example 18
Source File: ImageTiler.java    From orbit-image-analysis with GNU General Public License v3.0 5 votes vote down vote up
private PlanarImage makeTiledImage(PlanarImage img, int tileWidth, int tileHeight) {
    ImageLayout tileLayout = new ImageLayout(img);
    tileLayout.setTileWidth(tileWidth);
    tileLayout.setTileHeight(tileHeight);
    tileLayout.setSampleModel(img.getColorModel().createCompatibleSampleModel(tileWidth,tileHeight));
    tileLayout.setColorModel(img.getColorModel());
    RenderingHints tileHints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, tileLayout);
    ParameterBlock pb = new ParameterBlock();
    pb.addSource(img);
    PlanarImage pi = JAI.create("format", pb, tileHints);
    pi.getWidth();
    return pi;
}
 
Example 19
Source File: MedianFilter.java    From orbit-image-analysis with GNU General Public License v3.0 5 votes vote down vote up
public PlanarImage process() {
    if (!parameterSet) throw new IllegalStateException("parameters not set");
    PlanarImage pi = source;
    //   for (int i=0; i<numIter; i++) {
    ParameterBlock pb = new ParameterBlock();
    pb.addSource(pi);
    pb.add(MedianFilterDescriptor.MEDIAN_MASK_SQUARE);
    pb.add(radius);
    pi = JAI.create("MedianFilter", pb);
    //  }
    return pi;

}
 
Example 20
Source File: ImageFrame.java    From orbit-image-analysis with GNU General Public License v3.0 4 votes vote down vote up
/**
 * stores the current viewport as an image file. Executes a fileChooser for choosing the file and
 * displays a JOptionPane if successful.
 */
public void saveCurrentView() {
    JFileChooser fc = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("*.jpg", "jpg");
    fc.setFileFilter(filter);
    String snapShotFileName = recognitionFrame.getPicName();
    snapShotFileName = snapShotFileName.replaceAll(RawUtilsCommon.getExtension(snapShotFileName, false), "snapshot.jpg");
    fc.setSelectedFile(new File(snapShotFileName));
    int returnVal = fc.showSaveDialog(this);
    String fn = null;
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        fn = fc.getSelectedFile().getAbsolutePath();
        if (!fn.toLowerCase().endsWith(".jpg")) fn += ".jpg";
    }
    fc = null;
    this.repaint();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }
    if (fn != null) {
        BufferedImage bi;
        Robot robot;
        try {
            Rectangle r = recognitionFrame.getBounds();
            r.x += recognitionFrame.getLocationOnScreen().x;
            r.y += recognitionFrame.getLocationOnScreen().y;
            robot = new Robot();
            bi = robot.createScreenCapture(r);
            JPEGEncodeParam jpgParam = new JPEGEncodeParam();
            jpgParam.setQuality(0.85f);
            JAI.create("filestore", bi, fn, "JPEG", jpgParam);
            System.gc(); // forces JAI to close the filehandle
            logger.debug("finished writing");
            JOptionPane.showMessageDialog(this, "Screenshot successfully saved to " + fn, "Screenshot saved", JOptionPane.INFORMATION_MESSAGE);
        } catch (AWTException e) {
            logger.error("error saving screenshot", e);
        }
    }
}