Jai.widget

Hello,
I just started to use the jai api.
I have a very simple question : since the whole 'widget' sub-package seems to be deprecated, what are the classes that we are supposed to use instead ? I could not find that information in the javadoc.
Thanks in advance

Hi,
since 1.1.2 JAI includes com\sun\media\jai\widget\DisplayJAI.
Regards

Similar Messages

  • How to retain the same resolution while croping a tiff image using jai api

    Hi all,
    I have designed a program to crop a tiff image.But after croping the tiff,the resultant file resolution is not the same as the original source file.
    In the program,the source file Nadeshiko_v1_02.tif has the resolution(X) of 1200 DPI and resolution(Y) has 1200 DPI pixels.
    But after croping the resolution of output file is 100 DPI.
    Please give me some idea on how to retain the same resolution.
    <code>
    package jai;
    import java.awt.Frame;
    import java.awt.image.RenderedImage;
    import java.awt.image.renderable.ParameterBlock;
    import java.awt.image.renderable.RenderableImage;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import javax.imageio.*;
    import javax.imageio.stream.ImageOutputStream;
    import javax.media.jai.Interpolation;
    import javax.media.*;
    import javax.media.jai.JAI;
    import javax.media.jai.PlanarImage;
    import javax.media.jai.RenderedOp;
    import javax.media.jai.widget.ScrollingImagePanel;
    import com.sun.media.jai.codec.FileSeekableStream;
    import com.sun.media.jai.codec.SeekableStream;
    import com.sun.media.jai.codec.TIFFEncodeParam;
    import javax.media.jai.OperationDescriptorImpl;
    import java.io.*;
    import java.util.Iterator;
    import javax.media.jai.operator.*;
    // import javax.media.jai.widget.ScrollingImagePanel;
    public class crop {
              /** The main method. */
    public static void main(String[] args) {
    /* Validate input. */
    /* if (args.length != 1) {
    System.out.println("Usage: java JAISampleProgram " +
    "input_image_filename");
    // System.exit(-1);
    float a=(float) 70.3;
    float b=(float) 70.4;
    float c=(float) 3100.3;
    float d=(float) 5522.4;
    * Create an input stream from the specified file name
    * to be used with the file decoding operator.
    String TIFF="TIFF";
    FileSeekableStream stream = null;
    try {
         stream = new FileSeekableStream("D:\\tif images\\Nadeshiko_v1_02.tif");
    // stream = new FileSeekableStream("D:\\tif images\\Nadeshiko_v1_01.jpg");
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(0);
    // Load the source image from a Stream.
    RenderedImage im = JAI.create("stream", stream);
    RenderedImage image2= CropDescriptor.create(im, a, b, c, d, null);
    ScrollingImagePanel panel = new ScrollingImagePanel(image2, 100, 100);
    // Create a frame to contain the panel.
    Frame window = new Frame("JAI Image Cropping");
    window.add(panel);
    window.pack();
    // window.show();
    // Define the source and destination file names.
    // String inputFile = "D:\\tif images\\Nadeshiko_v1_05.tif";
    String outputFile = "D:\\tif images\\Nadeshiko_v1_04.tif";
    // Save the image on a file. We cannot just store it, we must set the image encoding parameters
    // to ensure that it will be stored as a tiled image.
    TIFFEncodeParam tep = new TIFFEncodeParam();
    tep.setWriteTiled(true);
    tep.setTileSize(80,80);
    JAI.create("filestore",image2,outputFile,"TIFF",null);
    try {
                   stream.close();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    </code>
    Thanks,
    Sanat Meher

    Try the following,
    TIFFEncodeParam tep = new TIFFEncodeParam();
    // Create {X,Y}Resolution fields.
    TIFFField fieldXRes = new TIFFField(0x11A, TIFFField.TIFF_RATIONAL,
                                        1, new long[][] {{DPI_X, 1}});
    TIFFField fieldYRes = new TIFFField(0x11B, TIFFField.TIFF_RATIONAL,
                                        1, new long[][] {{DPI_Y, 1}});
    tep.setExtraFields(new TIFFField[] {fieldXRes, fieldYRes});

  • Cannot get KeyListener to work with JAI ScrollImagePanel

    I am trying to display a TIF image and use the page up and page down keys to show page 1 and page 2 of the image. I started with an example for the JAI documentation.
    The problem is that I can't get the key event listener to "see" keystokes.
    I think ScrollImagePanel() is doing its own event listening and I don't know how to get at it.
    Here is the code:
    // http://java.sun.com/products/java-media/jai/forDevelopers/samples/MultiPageRead.java
    A single page of a multi-page TIFF file may loaded most easily by using the page
    parameter with the "TIFF" operator which is documented in the class comments of
    javax.media.jai.operator.TIFFDescriptor. This example shows a
    means of loading a single page of a multi-page TIFF file using the ancillary codec
    classes directly.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import java.io.IOException;
    import java.awt.image.RenderedImage;
    import java.awt.image.renderable.ParameterBlock;
    import javax.media.jai.*;
    import javax.media.jai.widget.*;
    import com.sun.media.jai.codec.*;
    public class MultiPageRead4 extends Frame
                implements KeyListener {                              //1
        ScrollingImagePanel panel;
        File file = null;
        ImageDecoder dec = null;
        RenderedImage op = null;
        // side to load, 0=front and 1=back
        static int imageToLoad = 0;
        /** The key code to flip between back and front images */
        private static final int FLIP_IMAGE_KEY1 = KeyEvent.VK_PAGE_UP;
        private static final int FLIP_IMAGE_KEY2 = KeyEvent.VK_PAGE_DOWN;
        /** Short cut key to exit the application */
        private static final int EXIT_KEY = KeyEvent.VK_ESCAPE;
        public MultiPageRead4(String filename) throws IOException {  //2
            super("Multi page TIFF Reader");
            // won't work here either
            // addKeyListener(this);
            addWindowListener(new WindowAdapter() {                  //3
               public void windowClosing(WindowEvent we) {           //4
               System.exit(0);
               }                                                     //4
            });                                                      //3
            if(file == null) {                                       //3
                file = new File(filename);
                SeekableStream s = new FileSeekableStream(file);
                TIFFDecodeParam param = null;
                dec = ImageCodec.createImageDecoder("tiff", s, param);
                System.out.println("Number of images in this TIFF: " +
                                   dec.getNumPages());
                // Which of the multiple images in the TIFF file do we want to load
                // 0 refers to the first, 1 to the second and so on.
                // int imageToLoad = 1;
                }                                                    //3
            // display side of tiff indicated by imageToLoad which is initialized to 0
            // and set by page up / page down
            displaySide();
            }                                                         //2
        // Methods required by the KeyListener interface.
         * Process a key being pressed. Does nothing as we wait for the
         * release before moving.
         * @param evt The event that caused this method to be called
        public void keyPressed(KeyEvent evt)
             System.out.println("Key pressed.");   // debug -- see if it works
            // do nothing
         * Process a key being type (press and release). Does nothing as this is
         * always dodgy about when we get the event. Better to look for the
         * release.
         * @param evt The event that caused this method to be called
        public void keyTyped(KeyEvent evt)
             System.out.println("Key typed.");    // debug -- see if it works
            // do nothing
         * Process a key being pressed. Does nothing as we wait for the
         * release before moving.
         * @param evt The event that caused this method to be called
        public void keyReleased(KeyEvent evt)
        {                                                              //2
            System.out.println("Key released.");  // debug -- see if it works
            switch(evt.getKeyCode())
            {                                                         //3
                case EXIT_KEY:
                    System.exit(0);
                    break;
                case FLIP_IMAGE_KEY1:
                   if(imageToLoad == 1) {                             //4
                      imageToLoad = 0;
                      displaySide();
                      break;
                   }                                                  //4
                case FLIP_IMAGE_KEY2:
                   if(imageToLoad == 0) {                             //4
                      imageToLoad = 1;
                      displaySide();
                      break;
                   }                                                  //4
            }                                                         //3
        }                                                             //2
        public void displaySide() {                                   //2
            try {
                op = new NullOpImage(dec.decodeAsRenderedImage(imageToLoad),
                                null,
                                OpImage.OP_IO_BOUND,
                                null);
                }  catch (java.io.IOException ioe) {
                      System.out.println(ioe);
        * Create a standard bilinear interpolation object to be
        * used with the �scale� operator.
           Interpolation interp = Interpolation.getInstance(
                 Interpolation.INTERP_BILINEAR);
        * Stores the required input source and parameters in a
        * ParameterBlock to be sent to the operation registry,
        * and eventually to the �scale� operator.
           ParameterBlock params = new ParameterBlock();
        // params.addSource(image1);
           params.addSource(op);
           params.add(0.70F); // x scale factor
           params.add(0.70F); // y scale factor
           params.add(0.0F); // x translate
           params.add(0.0F); // y translate
           params.add(interp); // interpolation method
        /* Create an operator to scale image1. */
           RenderedOp image2 = JAI.create("scale", params);
        /* Get the width and height of image2 + 3% */
           int width = (int)(image2.getWidth() * 1.03);
           int height = (int)(image2.getHeight() * 1.03);
        /* Attach image2 to a scrolling panel to be displayed. */
           panel = new ScrollingImagePanel(
              image2, width, height);
           panel.addKeyListener(this);
           // Display the original in a 800x800 scrolling window
           // panel = new ScrollingImagePanel(op, 1000, 600);
           add(panel);
           pack();
           show();
                                                                      //2
        public static void main(String [] args) {
            String filename = "034363331.TIF";
            try {
                MultiPageRead4 window = new MultiPageRead4(filename);
                }  catch (java.io.IOException ioe) {
                      System.out.println(ioe);
            System.out.println("finished.");
    // http://java.sun.com/products/java-media/jai/forDevelopers/samples/MultiPageRead.javaI can't get the KeyListener to act (or send the debug messages to System.out.println()).
    If "add( panel );" is removed and the comment before " keyListener(this); " in the constructor the key listening logic works -- of course no image is displayed.
    Thanks for any help.
    Bill Blalock

    Thanks for exanding your explanation. I am not yet skilled enough in Java to follow you completely but I am getting the idea.
    I would appreciate a code snippet using my example so I can better understand. In the mean time I found one way to make it work.
    In the example I eventually found that this change ..
           show();
           panel.requestFocus();enabled the key listener. Bringing the window, even clicking on the panel, didn't give it focus. I understand that the window has to have the focus in order for the key listener to function (different from the mouse listender). I don't understand why the application did not have "focus" even though it was on top and active.
    Oh well, lots to learn.
    Thanks for your suggestion!

  • How to Zoom the Image in JAI

    Hi,
    I need to zoom the image during the each button click.I have done 1 program ,but i coulnt able to change the parameter block's value each time.Take this program and just change the pic's path and run
    it ll show the pic,smaller than its actual size,because i changed the parameter block's value.this cahnge i want to do for each button click,please try to solve my problem,
    the code is
    import javax.swing.JFrame;
    import java.awt.Toolkit;
    import java.awt.Dimension;
    import java.awt.image.RenderedImage;
    import java.awt.image.BufferedImage;
    import java.awt.BasicStroke;
    import java.awt.Color;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import javax.swing.JPanel;
    import java.awt.image.renderable.ParameterBlock;
    import java.io.IOException;
    import javax.media.jai.Interpolation;
    import javax.media.jai.JAI;
    import javax.media.jai.*;
    import java.awt.geom.*;
    import java.awt.geom.AffineTransform;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.media.jai.RenderedOp;
    import com.sun.media.jai.codec.FileSeekableStream;
    import javax.media.jai.widget.ScrollingImagePanel;
    * This program decodes an image file of any JAI supported
    * formats, such as GIF, JPEG, TIFF, BMP, PNM, PNG, into a
    * RenderedImage, scales the image by 2X with bilinear
    * interpolation, and then displays the result of the scale
    * operation.
    public class JAISampleProgram extends DisplayJAI implements MouseListener
    JPanel jp=null;
    ParameterBlock params=null;
    Interpolation interp=null;
    RenderedImage image1;
    RenderedImage image2;
    RenderedImage rop;
    ScrollingImagePanel panel=null;
    JFrame jf=null;
    BufferedImage buff;
    Graphics2D graph;
    int width;
    int height;
    JAISampleProgram()
    JButton zoomin= new JButton(ico1);
    JButton zoomout = new JButton(ico2);
    jp = new JPanel();
    FileSeekableStream stream = null;
    try
    stream = new FileSeekableStream("D:/muthu/My Pictures/anniyan1.jpg");
    catch (IOException e)
    e.printStackTrace();
    System.exit(0);
    /* Create an operator to decode the image file. */
    image1 = JAI.create("stream", stream,null);
    * Create a standard bilinear interpolation object to be
    * used with the "scale" operator.
    interp = Interpolation.getInstance(
    Interpolation.INTERP_BICUBIC_2);
    * Stores the required input source and parameters in a
    * ParameterBlock to be sent to the operation registry,
    * and eventually to the "scale" operator.
    params = new ParameterBlock();
    params.addSource(image1);
    params.add(0.1f); // x scale factor
    params.add(0.1f); // y scale factor
    params.add(0.0F); // x translate
    params.add(0.0F); // y translate
    params.add(interp); // interpolation method
    /* Create an operator to scale image1. */
    image2 = JAI.create("scale", params,null);
    /* Get the width and height of image2. */
    width = image1.getWidth();
    height = image1.getHeight();
    /* Attach image2 to a scrolling panel to be displayed. */
    panel= new ScrollingImagePanel(image2, width, height);
    panel.setSize(400,300);
    setPreferredSize(new Dimension(image1.getWidth(),image1.getHeight()));
    buff = new BufferedImage(image1.getWidth(),image1.getHeight(), BufferedImage.TYPE_INT_RGB);
    width=image1.getWidth();
    height=image1.getHeight();
    graph = buff.createGraphics();
    graph.setStroke(new BasicStroke(2.0f));
    panel.addMouseListener(this);
    jp.add(zoomin);
    jp.add(zoomout);
    jf = new JFrame("sample");
    jf.setContentPane(panel);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    repaint();
    public void mouseClicked(MouseEvent e)
    ParameterBlock pb = new ParameterBlock();
    interp = Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2);
    pb = new ParameterBlock();
    pb.addSource(image2);
    pb.add(0.5f); // x scale factor
    pb.add(0.5f); // y scale factor
    pb.add(0.0F); // x translate
    pb.add(0.0F); // y translate
    pb.add(interp); // interpolation method
    rop = JAI.create("scale", params,null);
    panel= new ScrollingImagePanel(rop, width, height);
    panel.setSize(400,300);
    setPreferredSize(new Dimension(image1.getWidth(),image1.getHeight()));
    buff = new BufferedImage(image1.getWidth(),image1.getHeight(), BufferedImage.TYPE_INT_RGB);
    width=image1.getWidth();
    height=image1.getHeight();
    graph = buff.createGraphics();
    graph.setStroke(new BasicStroke(2.0f));
    repaint();
    public void mouseEntered(MouseEvent e)
    public void mouseExited(MouseEvent e){}
    public void mousePressed(MouseEvent e){}
    public void mouseReleased(MouseEvent e){}
    public synchronized void paintComponent(Graphics g)
    panel.paintComponents(g);
    Graphics2D g2d = (Graphics2D)g;
    g = jp.getGraphics();
    g2d.setColor(Color.BLUE);
    g2d.drawLine(50,50,100,100);
    graph.setColor(Color.yellow);
    g.drawLine(60,60,120,120);
    g2d.drawRenderedImage(rop,AffineTransform.getTranslateInstance(100.00,100.00));
    /* params = params.set(0.1f,0);
    params = params.set(0.1f,1); */
    public static void main(String[] args)
    /* Validate input.
    * Create an input stream from the specified file name
    * to be used with the file decoding operator.
    JAISampleProgram jai = new JAISampleProgram();
    /* Create a frame to contain the panel. */
    jai.jf.pack();
    Toolkit theKit=Toolkit.getDefaultToolkit();
    Dimension dim=theKit.getScreenSize();
    int scrWidth=dim.width;
    int scrHeight=dim.height;
    jai.jf.setSize(scrWidth,scrHeight);
    jai.jf.show();
    }

    scale your Graphics2D object
    http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Graphics2D.html#scale(double,%20double)
    Also check the documentation of
    http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JComponent.html#paint(java.awt.Graphics)
    and see if your code would be better in paint(java.awt.Graphics) instead of paintComponent(Graphics g)

  • JAI - problem displaying additional pages from multi-page image

    Hi,
    I have 10 page multipage tiff images. And i would like to show the images one-by-one on a ScrollingImagePanel.
    I have a Main frame with two panels. Panel1 which shows the ScrollingImagePanel.
    And Panel2 has two buttons. LOAD Button show the 1st page on the ScrollingImagePanel.
    And NEXT button is suppose to show the 2nd page and continue until the end of the multipage images.
    I am having problem with the NEXT button. I wrote a program that show the page number and page height
    on the output screen. It shows the page# and different heights. But it would not show the images on the ScrollingImagePanel.
    It just shows the 1st page. I would appreciate if you can help me out with this problom.
    Please find the code which is written in JBuilder.
    // Main class
    package untitled1;
    import java.awt.*;
    import javax.swing.UIManager;
    import java.awt.*;
    import java.io.File;
    import java.io.IOException;
    import java.awt.Frame;
    import java.awt.image.RenderedImage;
    import javax.media.jai.widget.ScrollingImagePanel;
    import javax.media.jai.NullOpImage;
    import javax.media.jai.OpImage;
    import com.sun.media.jai.codec.SeekableStream;
    import com.sun.media.jai.codec.FileSeekableStream;
    import com.sun.media.jai.codec.TIFFDecodeParam;
    import com.sun.media.jai.codec.ImageDecoder;
    import com.sun.media.jai.codec.ImageCodec;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2002</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    public class Application1 {
    boolean packFrame = false;
    //Construct the application
    public Application1() {
    Frame2 frame = new Frame2();
    frame.setSize(820,700);
    //Validate frames that have preset sizes
    //Pack frames that have useful preferred size info, e.g. from their layout
    if (packFrame) {
    frame.pack();
    else {
    frame.validate();
    //Center the window
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = frame.getSize();
    if (frameSize.height > screenSize.height) {
    frameSize.height = screenSize.height;
    if (frameSize.width > screenSize.width) {
    frameSize.width = screenSize.width;
    frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
    frame.setVisible(true);
    //Main method
    public static void main(String[] args) {
    new Application1();
    // Frame2 Class
    package untitled1;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.UIManager;
    import java.io.File;
    import java.io.IOException;
    import java.awt.Frame;
    import java.awt.image.RenderedImage;
    import javax.media.jai.widget.ScrollingImagePanel;
    import javax.media.jai.NullOpImage;
    import javax.media.jai.OpImage;
    import com.sun.media.jai.codec.SeekableStream;
    import com.sun.media.jai.codec.FileSeekableStream;
    import com.sun.media.jai.codec.TIFFDecodeParam;
    import com.sun.media.jai.codec.ImageDecoder;
    import com.sun.media.jai.codec.ImageCodec;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.*;
    import java.awt.image.renderable.ParameterBlock;
    import javax.media.jai.*;
    import javax.media.jai.widget.*;
    import com.sun.media.jai.codec.*;
    import java.util.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2002</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    public class Frame2 extends Frame {
    JPanel jPanel1 = new JPanel();
    JPanel jPanel2 = new JPanel();
    JButton loadButton = new JButton();
    public static ScrollingImagePanel panel, panels;
    JButton nextButton = new JButton();
    public String filename= "144.tif";
    public File file;
    public SeekableStream s;
    public ImageDecoder dec;
    protected int imageWidth, imageHeight;
    public int nextpage = 1;
    public RenderedOp image2 = null;
    public RenderedImage op = null;
    //Frame Constructor
    public Frame2() {
    try {
    jbInit();
    catch(IOException e) {
    e.printStackTrace();
    private void jbInit() throws IOException {
    this.setLayout(null);
    this.addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    this_windowClosing(e);
    jPanel1.setBackground(Color.white);
    jPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
    jPanel1.setBounds(new Rectangle(1, 7, 816, 648));
    jPanel1.setLayout(null);
    jPanel2.setBackground(Color.lightGray);
    jPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
    jPanel2.setBounds(new Rectangle(1, 657, 816, 42));
    loadButton.setText("Load");
    loadButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    try{                          
    loadButton_actionPerformed(e);
    catch(IOException IOE){
    System.out.println(IOE);
    nextButton.setText("Next");
    nextButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    try {
    nextButton_actionPerformed(e);
    catch(IOException IOE){
    System.out.println(IOE);
    this.setResizable(false);
    this.add(jPanel1, null);
    this.add(jPanel2, null);
    jPanel2.add(loadButton, null);
    jPanel2.add(nextButton, null);
    void this_windowClosing(WindowEvent e) {
    System.exit(0);
    //Load Image Button
    void loadButton_actionPerformed(ActionEvent e) throws IOException { 
    file = new File(filename);
    s = new FileSeekableStream(file);
    dec = ImageCodec.createImageDecoder("tiff", s, null);
    RenderedImage op =
    new NullOpImage(dec.decodeAsRenderedImage(),
    null,
    OpImage.OP_IO_BOUND,
    null);
    Interpolation interp = Interpolation.getInstance(Interpolation.INTERP_BILINEAR);
    ParameterBlock params = new ParameterBlock();
    params.addSource(op);
    params.add(0.55F); // x scale factor
    params.add(0.335F); // y scale factor
    params.add(0.00F); // x translate
    params.add(0.00F); // y translate
    params.add(interp); // interpolation method
    image2 = JAI.create("scale", params);
    int width = (int)(image2.getWidth() * .73);
    int height = (int)(image2.getHeight() * .73);
    panel = new ScrollingImagePanel(image2, 819, 648);
    jPanel1.add(panel);
    this.setVisible(true);
    //Next Image Button
    void nextButton_actionPerformed(ActionEvent e) throws IOException {
    TIFFDecodeParam param = null;
    file = new File(filename);
    s = new FileSeekableStream(file);
    dec = ImageCodec.createImageDecoder("tiff", s, param);
    nextpage++;
    System.out.println(nextpage);
    RenderedImage op1 =
    new NullOpImage(dec.decodeAsRenderedImage(nextpage),
    null,
    OpImage.OP_IO_BOUND,
    null);
    Interpolation interp = Interpolation.getInstance(Interpolation.INTERP_BILINEAR);
    ParameterBlock params = new ParameterBlock();
    params.addSource(op1);
    params.add(0.55F); // x scale factor
    params.add(0.335F); // y scale factor
    params.add(0.00F); // x translate
    params.add(0.00F); // y translate
    params.add(interp); // interpolation method
    image2 = JAI.create("scale", params);
    int width = (int)(image2.getWidth() * .73); //1.03);
    int height = (int)(image2.getHeight() * .73); //1.03);
    panels = new ScrollingImagePanel(image2, width, height);
    System.out.println(op1.getHeight());
    jPanel1.add(panels);
    this.setVisible(true);
    thanks in advance

    Take a look at this code.
    //Search the Policynumber
    void searchButton_actionPerformed(ActionEvent e) {
    try{
    nextButton.setEnabled(false);
    previousButton.setEnabled(false);
    String query = "SELECT * FROM PINFO WHERE POLICYNUMBER = '" +
    searchTextfield.getText().toUpperCase() + "'";
    ResultSet rs = Application1.stmt.executeQuery(query);
    while(rs.next()){
    pid = (rs.getInt("PID"));
    policynumber = rs.getString("POLICYNUMBER");
    firstName = rs.getString("FIRSTNAME");
    lastName = rs.getString("LASTNAME");
    jLabel2.setText(policynumber);
    jLabel3.setText(firstName);
    jLabel4.setText(lastName);
    catch(SQLException ex){
    System.err.println("SQLException: " + ex.getMessage());
    try{
    String query = "SELECT * FROM (UNMATCH U LEFT JOIN DOCUMENTTYPE D ON U.DOCUMENTTYPE=D.DOCNUMBER) WHERE PID = '" + pid + "' ORDER BY D.DOCUMENTCODE";
    ResultSet rs1 = Application1.stmt.executeQuery(query);
    clearJList();
    v.removeAllElements();
    jList1.setListData(v);
    v1.clear();
    while(rs1.next()){
    documentcode = rs1.getString("DOCUMENTCODE");
    uindex = rs1.getString("UINDEX");
    v.add(documentcode);
    v1.add(uindex);
    jList1.setListData(v);
    clearTextfield();
    catch(SQLException s){
    System.err.println("SQLException: " + s.getMessage());
    public void clearJList(){
    jList1.setListData(v);
    public void clearTextfield(){
    searchTextfield.setText("");
    // ****** Loads the selected Image
    void jList1_mouseClicked(MouseEvent e){
    try{
    vector.clear();
    nextpage = 1;
    currentpage = 1;
    nextButton.setEnabled(true);
    previousButton.setEnabled(false);
    if (spane != null)
    jPanel1.removeAll();
    seek = null;
    String query1 = "SELECT * FROM UNMATCH WHERE UINDEX = '" + v1.get(jList1.getSelectedIndex()).toString() + "'";
    rs2 = Application1.stmt.executeQuery(query1);
    while (rs2.next()){
    stream = rs2.getBinaryStream("IMAGE");
    seek = new MemoryCacheSeekableStream(stream);
    TIFFDecodeParam param = null;
    dec = ImageCodec.createImageDecoder("tiff", seek, param);
    try{
    totalPages = dec.getNumPages();
    jLabel1.setText("Page 1 of "+totalPages);
    if (nextpage==totalPages)
    nextButton.setEnabled(false);
    op1 =
    new NullOpImage(dec.decodeAsRenderedImage(nextpage-1),
    null,
    OpImage.OP_IO_BOUND,
    null);
    vector.addElement(op1);
    // ParameterBlock params = new ParameterBlock();
    // params.addSource(op1);
    // panel = new DisplayJAI(op1);
    panel = new DisplayJAI((RenderedImage)vector.elementAt(0));
    spane = new JScrollPane(panel);
    jPanel1.add(spane);
    jPanel1.validate();
    this.setVisible(true);
    catch(IOException dfs){
    } // while
    } // try
    catch(SQLException s){
    System.err.println("SQLException: " + s.getMessage());
    // Next Image
    void nextButton_actionPerformed(ActionEvent e) {
    try{
    if (spane != null)
    jPanel1.removeAll();
    ++nextpage;
    if (nextpage==totalPages)
    nextButton.setEnabled(false);
    previousButton.setEnabled(true);
    jLabel1.setText("Page " + nextpage +" of "+totalPages);
    TIFFDecodeParam param = null;
    dec = ImageCodec.createImageDecoder("tiff", seek, param);
    currentpage = nextpage;
    ParameterBlock paramblock = new ParameterBlock();
    paramblock.addSource(op1);
    vector.addElement(new NullOpImage(dec.decodeAsRenderedImage(nextpage-1),
    null,
    OpImage.OP_IO_BOUND,
    null));
    panel = new DisplayJAI((RenderedImage)vector.elementAt(currentpage-1));
    // panel = new DisplayJAI(op1);
    spane = new JScrollPane(panel);
    jPanel1.add(spane);
    setVisible(true);
    catch(IOException o){
    System.out.println(o);
    finally{
    // PreviousButton
    void previousButton_actionPerformed(ActionEvent e) {
    try{
    if (spane != null)
    jPanel1.removeAll();
    --nextpage;
    if (nextpage==1)
    previousButton.setEnabled(false);
    nextButton.setEnabled(true);
    jLabel1.setText("Page " + nextpage +" of "+totalPages);
    TIFFDecodeParam param = null;
    dec = ImageCodec.createImageDecoder("tiff", seek, param);
    currentpage = nextpage;
    vector.addElement(new NullOpImage(dec.decodeAsRenderedImage(nextpage-1),
    null,
    OpImage.OP_IO_BOUND,
    null));
    panel = new DisplayJAI((RenderedImage)vector.elementAt(currentpage-1));
    spane = new JScrollPane(panel);
    jPanel1.add(spane);
    setVisible(true);
    catch(IOException o){
    System.out.println(o);
    // Zoom ComboBox Item Select
    void jComboBox1_itemStateChanged(ItemEvent e) {
    if (e.getStateChange() == ItemEvent.DESELECTED)
    if (spane != null)
    jPanel1.removeAll();
    Interpolation interp = Interpolation.getInstance(Interpolation.INTERP_BICUBIC);
    ParameterBlock params = new ParameterBlock();
    params.addSource(op1);
    params.add(Float.valueOf(jComboBox1.getSelectedItem().toString()).floatValue()/100.0f);
    params.add(Float.valueOf(jComboBox1.getSelectedItem().toString()).floatValue()/100.0f);
    params.add(0.0F);
    params.add(0.0F);
    params.add(interp);
    // image2 = JAI.create("scale",params);
    vector.add(currentpage-1,JAI.create("scale",params));
    panel = new DisplayJAI((RenderedOp)vector.elementAt(currentpage-1));
    spane = new JScrollPane(panel);
    jPanel1.add(spane);
    jPanel1.validate();
    this.setVisible(true);
    repaint();
    // Rotate ComboBox Item Select
    void jComboBox2_itemStateChanged(ItemEvent e) {
    if (e.getStateChange() == ItemEvent.DESELECTED)
    if (spane != null)
    jPanel1.removeAll();
    type =null;
    type = transposeTypes[jComboBox2.getSelectedIndex()];
    ParameterBlock pb = new ParameterBlock();
    pb.addSource((RenderedImage)vector.elementAt(currentpage-1));
    pb.add(type);
    PlanarImage im2 = JAI.create("transpose", pb, renderHints);
    vector.add(currentpage-1,im2);
    panel = new DisplayJAI((RenderedOp)vector.elementAt(currentpage-1));
    spane = new JScrollPane(panel);
    jPanel1.add(spane);
    jPanel1.validate();
    this.setVisible(true);
    void printButton_actionPerformed(ActionEvent e) {
    print();
    protected void print() {
    PrinterJob pj = PrinterJob.getPrinterJob();
    pj.setPrintable(this);
    // PageFormat format = pj.pageDialog(pj.defaultPage());
    // Book bk = new Book();
    // bk.append(this,pj.defaultPage());
    // pj.setPageable(bk);
    if(pj.printDialog()){
    try{
    pj.print();
    catch(Exception e){
    System.out.println(e);
    else{
    System.out.println("Did Not Print Any Pages");
    public int print(Graphics g, PageFormat f, int pageIndex){
    if(pageIndex >= 1){
    return Printable.NO_SUCH_PAGE;
    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(f.getImageableX(), f.getImageableY());
    if(op1 != null){
    double scales = Math.min(f.getImageableWidth()/ op1.getWidth(), f.getImageableHeight()/ op1.getHeight());
    g2d.scale(scales,scales);
    printImage(g2d, op1);
    return Printable.PAGE_EXISTS;
    else{
    return Printable.NO_SUCH_PAGE;
    public void printImage(Graphics2D g2d, RenderedImage image){
    if((image == null)|| (g2d == null)) return;
    int x = printLoc.x;
    int y = printLoc.y;
    AffineTransform at = new AffineTransform();
    at.translate(x,y);
    g2d.drawRenderedImage(image,at);
    public void setPrintLocation(Point d) {
    printLoc = d;
    public Point getPrintLocation() {
    return printLoc;

  • Regarding JAI

    hai,
    I want to run a program using JAI...I have installed it and have set the claspath also..but when i run the program it results in error....
    symbol : method add (javax.media.jai.widget.ScrollingImagePanel)
    location: class RemoteImagingTest
    add(new ScrollingImagePanel(sum,
    ^
    RemoteImagingTest.java:138: cannot resolve symbol
    symbol : method add (javax.media.jai.widget.ScrollingImagePanel)
    location: class RemoteImagingTest
    add(new ScrollingImagePanel(remoteImage,
    ^
    RemoteImagingTest.java:145: cannot resolve symbol
    symbol : method add (javax.media.jai.widget.ScrollingImagePanel)
    location: class RemoteImagingTest
    add(new ScrollingImagePanel(remoteImage,
    ^
    RemoteImagingTest.java:162: cannot resolve symbol
    symbol : method add (javax.media.jai.widget.ScrollingImagePanel)
    location: class RemoteImagingTest
    add(new ScrollingImagePanel(remoteImage,
    ^
    RemoteImagingTest.java:167: cannot resolve symbol
    symbol : method pack ()
    location: class RemoteImagingTest
    pack();
    ^
    RemoteImagingTest.java:168: cannot resolve symbol
    symbol : method show ()
    location: class RemoteImagingTest
    show();
    Please help me solve these errors...
    Thankyou
    Padma.

    Are you trying to use the examples (from tutorial etc.)?
    If so there are some classes that they use that you have to get the source code to add to your project.
    And maybe you need to add the JAI to your JRE (i.e. the one your computer uses when running Java programs as opposed to the one in the JDK).
    These are some of the problems I had when I first started using the JAI.

  • JAI and grayscale problems

    Hi!
    My problem concerns grayscale. First I load tiff-image from a file (OK) and then I want to change its colors to grayscale and after that I save that converted picture as Bmp, but this is not working. I have tried codes that I found from forum, but those arent helping me.So, in brief how to convert tiff image to grayscale image and sav it as Bmp. Could anyone give me a code? This grayscale seems to be problem for many people.

    You can convert tiff image to grey image by:
    public PlanarImage convertColor(PlanarImage src_image){
    double[][] matrix = {
    { .114D, 0.587D, 0.299D, 0.0D }
    // Create the ParameterBlock.
    ParameterBlock pb = new ParameterBlock();
    pb.addSource(src_image);
    pb.add(matrix);
    // Perform the band combine operation.
    return (PlanarImage)JAI.create("bandcombine", pb, null);
    Write you codes like this:
    PlanarImage srcc=convertColor(planarImage);
    BMPWriter bmpW=new BMPWriter(srcc,fc.getCurrentDirectory().getPath(),file.getName());               bmpW.saveImage();
    Following is class used for save image to bmp
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.image.renderable.*;
    import java.io.*;
    import javax.media.jai.*;
    import javax.media.jai.widget.*;
    import com.sun.media.jai.codec.*;
    import javax.swing.*;
    public class BMPWriter {
         private PlanarImage src;
         private String outFilePath;
         private String outFileName;
    private ImageEncoder encoder = null;
         BMPEncodeParam encodeParam=null;
    // Create the image encoder.
    private void encodeImage(PlanarImage img, FileOutputStream out)
              ImageEncoder encoder = ImageCodec.createImageEncoder("BMP", out,
    encodeParam);
              if (encoder==null){
                   System.out.println("encoder is null");
                   return;
              if (img==null){
                   System.out.println("img is null");
                   return;
              try {
    // encoder.encode(img);
                        encoder.encode(img);
    out.close();
              catch (IOException e) {
    System.out.println("IOException at encoding..");
    System.exit(1);
    private FileOutputStream createOutputStream(String outFile) {
    FileOutputStream out = null;
    try {
    out = new FileOutputStream(outFile);
    } catch(IOException e) {
    System.out.println("IOException.");
    System.exit(1);
    return out;
    public BMPWriter(PlanarImage img,String outFilePath,String outFileName) {
              this.outFilePath=outFilePath;
              this.outFileName=outFileName;
              src=img;
         public void saveImage(){
              FileOutputStream out1 = createOutputStream(outFilePath+File.separator+outFileName);
              if (out1==null){
                   System.out.println("out1 is null");
                   return;
    double[] constants = new double[3];
    constants[0] = 0.0;
    constants[1] = 0.0;
    constants[2] = 0.0;
    ParameterBlock pb = new ParameterBlock();
    pb.addSource(src);
    pb.add(constants);
              encodeParam = new BMPEncodeParam();
    encodeImage(src, out1);
    }

  • JAI API...Why color change?

    I wanna to use n parts of pictures to be one. When I use png/gif, production picture looks normal. Why I use
    jpeg/bmp, my production picture will change any color to red. Please tell me why? The reason is "outImage.setSample"??
    ========================================================================================
    import javax.media.jai.*;
    import javax.media.jai.widget.*;
    import javax.media.jai.iterator.*;
    public class imageConvert3 {
         public String align;
         public String[] inputFiles;
         public int parts;
         public imageConvert3() {
         } // --- < public imageConvert3() > ---
         public String getAlign() {
              return this.align;
         } // --- < public String getAlign() > ---
         public String[] getInputFiles() {
    return this.inputFiles;
         } // --- < public String[] getInputFiles() > ---
         public int getParts() {
    return this.parts;
         } // --- end of < public void getParts() > ---
         public void setAlign(String align) {
              this.align = align;
         } // --- end of < public void setAlign(String align) > ---
         public void setInputFiles(String[] inputFiles) {
    this.inputFiles = inputFiles;
         } // --- end of < public void setInputFiles(String[] inputFiles) > ---
         public void setParts(int parts) {
    this.parts = parts;
         } // --- end of < public void setParts(int parts) > ---
         public String convert() {
              RenderedOp[] inputPictures = new RenderedOp[inputFiles.length];
              RandomIter[] iterPictures = new RandomIter[inputFiles.length];
              TiledImage outImage;
              // setting second File Name
              String sfName = inputFiles[0].substring(inputFiles[0].lastIndexOf(".") + 1, inputFiles[0].length());
              String fName = "";
              // <0>Setting File Name
              // <1>Create input image
              // <2>Use the access the source image
              for (int i = 0; i < inputFiles.length; i++) {
                   //<0>
                   fName = fName + inputFiles.substring(0, inputFiles[i].lastIndexOf("."));
                   //<1>
                   inputPictures[i] = JAI.create("fileload", "images\\" + inputFiles[i]);               
                   //<2>
                   iterPictures[i] = RandomIterFactory.create(inputPictures[i], null);
              } // --- < for (int i = 0; i < inputFiles.length(); i++) > ---
              int bands = inputPictures[0].getSampleModel().getNumBands();
              // Define height/width
              int height, unitHeight;
              int width, unitWidth;
              unitHeight = inputPictures[0].getHeight();
              unitWidth = inputPictures[0].getWidth();
              if (align.equals("vertical")) {
                   height = unitHeight * parts;
                   width = unitWidth;
              else {
                   height = unitHeight;
                   width = unitWidth * parts;
              } // --- end of < if (align.equals("vertical")) > ---
              // Create the out image
              outImage = new TiledImage(inputPictures[0].getMinX(),
                                            inputPictures[0].getMinY(),
                                            width,
                                            height,
                                            inputPictures[0].getMinX(),
                                            inputPictures[0].getMinY(),
                                            inputPictures[0].getSampleModel(),
                                            inputPictures[0].getColorModel());
              // setSample
              for (int cnts = 0; cnts < parts; cnts++) {
                   int yy = 0;
                   System.out.println("Generate " + inputFiles[cnts] + "---\n");
                   if (align.equals("vertical")) {
                        for (int y = cnts * unitHeight; y < (cnts + 1) * unitHeight ; y++) {
                             int xx = 0;
                             for (int x = 0; x < unitWidth; x++) {
                                  try {
                                       outImage.setSample(x, y, 0, iterPictures[cnts].getSample(xx, yy, 0));
                                  } catch (Exception ec) {
                                  xx++;
                             } // --- < for (int x = 0; x < unitWight; x++) > ---
                             yy++;
                        } // --- < for (int y = cnts * unitHeight; y < (cnts + 1) * unitHeight ; y++) > ---
                   else {
                        for (int y = 0; y < unitHeight ; y++) {
                             int xx = 0;
                             for (int x = cnts * unitWidth; x < (cnts + 1 ) * unitWidth; x++) {
                                  try {
                                       outImage.setSample(x, y, 0, iterPictures[cnts].getSample(xx, yy, 0));
                                  } catch (Exception ec) {
                                  xx++;
                             } // --- < for (int y = 0; y < unitHeight ; y++) > ---
                             yy++;
                        } // --- < for (int x = cnts * unitWight; x < (cnts + 1 ) * unitWight; x++) > ---
                   } // --- < if (align.equals("vertical")) > ---
              } // --- < for (int x = 0; x < unitWight; x++) > ---
              // Write the image to a file
              RenderedOp op = JAI.create("filestore",
                                            outImage,
                                            "images\\new\\" +
                                            fName + "." + sfName,
                                            "PNG",
                                            null);
              return "scuccessful!";
         } // --- end of < public String mergeParts2OneImage() > ---
         public static void main (String args[]) {
              imageConvert3 img = new imageConvert3();
              String[] flist = new String[3];
              flist[0] = "head1.png";
              flist[1] = "body1.png";
              flist[2] = "foot1.png";
              img.setAlign("horizontal");
              img.setParts(3);
              img.setInputFiles(flist);
              img.convert();
    } // --- end of < public class imageConvert3 > ---
    ========================================================================================
    Thanks a lot!

    The samples you are writing into the outImage object may not be compatible with each other, so that is probably why your resulting colors are invalid. You need to add compatible samples. I am assuming this problems stems from the fact that your source data is coming from various image file types, which most likely have different sample/color types among them.

  • Javax.media.jai not in jmf.jar

    I’ve download JMF 2.1.1e from
    http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/download.html
    and installed it. However it does not seem to contain the javax.media.jai or com.sun.media.jai packages as per the documentation :-
    http://java.sun.com/products/java-media/jai/forDevelopers/jai-apidocs/index.html
    I checked the contains of the jmf.tar and and the other jars that came with the download
    eg the following can not be found
    import javax.media.jai.widget.ScrollingImagePanel;
    import javax.media.jai.NullOpImage;
    import javax.media.jai.OpImage;
    import com.sun.media.jai.codec.SeekableStream;
    import com.sun.media.jai.codec.FileSeekableStream;
    import com.sun.media.jai.codec.TIFFDecodeParam;
    import com.sun.media.jai.codec.ImageDecoder;
    import com.sun.media.jai.codec.ImageCodec;
    So have I done something wrong, is this code no long in the jmf.jar, or is the documentation wrong ?

    Thanks, that got me the jai_imageio.jar , however this jar does not contain the any of the following packages
    import javax.media.jai.widget.ScrollingImagePanel;
    import javax.media.jai.NullOpImage;
    import javax.media.jai.OpImage;
    import com.sun.media.jai.codec.SeekableStream;
    import com.sun.media.jai.codec.FileSeekableStream;
    import com.sun.media.jai.codec.TIFFDecodeParam;
    import com.sun.media.jai.codec.ImageDecoder;
    import com.sun.media.jai.codec.ImageCodec;
    are they in another jar that I have not included, or do I need to get them from somewhere else?

  • Right way to add page.

    Hi,
    Say A.tiff contains 6 pages and B.tiff contains 5 pages. I need to 5 pages of B.tiff into A.tiff, so that A.tiff contains 11 pages. Can someone pls show me the fastest way of acheiving this ?
    Currently I am using ImageDecoder to decode A and B to put all the contents of 11 pages into vector, then use ImageEncoder to encode them as new image say C.tiff. This method is very slow. I hope someone can advise.
    Regards,
    Kok.

    When I try this program proposed by JAI, the C.tiff only contains 2 pages in C.tiff, 1 from A.tiff and the other one from B.tiff. Where went wrong ?
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.image.renderable.*;
    import java.io.*;
    import java.util.*;
    import javax.media.jai.*;
    import javax.media.jai.widget.*;
    import com.sun.media.jai.codec.*;
    import com.sun.media.jai.codecimpl.*;
    * Reads all specified files and stores them into a single multi-page TIFF
    * file called "multipage.tif".
    * Usage: java TIFFIOTest file1 [file2 [file3 ...]]
    public class TIFFIOTest {
        public static void main(String[] args) {
            new TIFFIOTest(args);
        public saveasone(String[] fileNames) {
            RenderedImage[] srcs = new RenderedImage[fileNames.length];
            ParameterBlock pb = (new ParameterBlock());
            pb.add(fileNames[0]);
            RenderedImage src0 = JAI.create("fileload", pb);
            ArrayList list = new ArrayList(srcs.length - 1);
            for(int i = 1; i < srcs.length; i++) {
                pb = (new ParameterBlock());
                pb.add(fileNames);
    list.add(JAI.create("fileload", pb));
    TIFFEncodeParam param = new TIFFEncodeParam();
              param.setCompression(TIFFEncodeParam.COMPRESSION_JPEG_TTN2);
    param.setExtraImages(list.iterator());
    pb = (new ParameterBlock());
    pb.addSource(src0);
    pb.add("multipage.tiff").add("tiff").add(param);
    JAI.create("filestore", pb);

  • Multiple SQL Update within Parent Query

    I am tring to extract an image from within a MS SQL image field,
    opening the image using JAI, getting the src.getWidth() & src.getHeight
    () of each item within the database, and then writing the width and
    height back into the database. Everything works except when I goto
    write the values into the database - the page (when loading) continues
    to work and work and work until I restart the tomcat service. I do not
    understand why this would occur, and what is even stranger - I have
    very similar code i used for resizing images in the database into a
    thumbnail - display and original file sizes using a similar approach...
    and that works with out a problem...
    I have tried the code with out the inner update query - it works. I
    tried with just the selection of a single specific item in the first
    query and that works, but when I try multiple updates the second query
    appears to stall.
    The code is as follows.:
    <%@ page language="java" import="javax.servlet.*,javax.servlet.http.*,java.io.*,java.util.*,java.sql.*,javax.media.jai.*,java.awt.*,java.awt.image.*,java.awt.Graphics.*,java.awt.geom.*,java.awt.image.renderable.*,javax.media.jai.widget.*,com.jspsmart.upload.*,java.net.*,com.sun.media.jai.codec.*"%>
    <jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" />
    <%
         // Variables
         int count=0;
         int width                                             = 0;
         int height                                             = 0;
         String vFileName                                   = "";
         String vFileExt                                        = "";
         String vFileID                                        = "";
         String format                                        = "0";
         // Connect to the database
         Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
         Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://206.152.227.62:1433;DatabaseName=WWWBBD;User=wwwbbd;Password=bbd1412");
         //Create the statement
         Statement sqlGetPics                              = con.createStatement();
         Statement sqlUpdate                                   = con.createStatement();
         //build the query
         String qryGetPics                                   = "SELECT TOP 5 FileID, FileExt, FileName, AdjFile = CASE WHEN FullFile IS NULL THEN Display ELSE FullFile END FROM FileStore WHERE (UPPER(FileExt) = '.JPG' OR UPPER(FileExt) = '.TIF' OR UPPER(FileExt) = '.GIF' OR UPPER(FileExt) = '.BMP') AND (NOT Display IS NULL OR NOT FullFile IS NULL)";
         //execute the query
         ResultSet rsGetPics                                   = sqlGetPics.executeQuery(qryGetPics);
         // Initialization
         SmartUpload uploader                              = new SmartUpload();
         uploader.initialize(getServletConfig(),request,response);
         mySmartUpload.initialize(getServletConfig(), request, response);
         // Upload
         mySmartUpload.upload();
         while (rsGetPics.next()) {
              vFileID                                             = rsGetPics.getString("FileID");
              vFileExt                                        = rsGetPics.getString("FileExt");
              vFileName                                        = rsGetPics.getString("FileName") + vFileExt;
              width                                             = 0;
              height                                             = 0;
              uploader.fieldToFile(rsGetPics, "AdjFile", "/upload/" + vFileName);
              if (vFileExt.equalsIgnoreCase(".JPG") || vFileExt.equalsIgnoreCase(".JPEG"))
                   format                                        = "JPEG";
              else if (vFileExt.equalsIgnoreCase(".TIF") || vFileExt.equalsIgnoreCase(".TIFF"))
                   format                                        = "TIFF";
              else if (vFileExt.equalsIgnoreCase(".GIF"))
                   format                                        = "JPEG";
              else if (vFileExt.equalsIgnoreCase(".BMP"))
                   format                                        = "BMP";
              else
                   format                                        = "0";
              // update the width & height
              if (format != "0")
                   try
                        //Opens the image
                        RenderedImage src                    = JAI.create("fileload","d:\\servers\\tomcat\\webapps\\jsp\\upload\\" + vFileName);
                        width                                   = src.getWidth();
                        height                                   = src.getHeight();
                        java.io.File imageFile               = new java.io.File("d:\\servers\\tomcat\\webapps\\jsp\\upload\\" + vFileName);
                        InputStream is                         = new FileInputStream(imageFile);
                        //build the query
                        String qryUpdate                    = "UPDATE FileStore SET Width = " + width + ", Height = " + height + " WHERE FileID = " + vFileID;
                        //execute the query
                        ResultSet rsUpdate                    = sqlUpdate.executeQuery(qryUpdate);
                        %>[<%=width%>x<%=height%>:<%=vFileID%>:<%=qryUpdate%>]<BR><%
                   catch(Exception e)
                        {out.println("An error occurs : " + e.toString());}               
              count++;          
         //rsUpdate.close();
         sqlUpdate.close();
    %>
    <HTML>
    <HEAD>
         <TITLE>Repair Files</TITLE>
    </HEAD>
    <BODY>
    <%=count%> files updated in the database.
    </BODY>
    </HTML>

    BTW - I also tried this with a prepared statment query... no good.

  • How to control the pixcel size in given tiff image

    Hai
    I loaded tiff image into the Frame by using the jai_core.jar and jai_codec.jar files. I am unable to control the pixcel size. It displaied default size. How to restract the pixcel on the image in Frame.
    import java.io.File;
    import java.io.IOException;
    import java.awt.Frame;
    import java.awt.image.RenderedImage;
    import javax.media.jai.widget.ScrollingImagePanel;
    import javax.media.jai.ImageLayout;
    import javax.media.jai.NullOpImage;
    import javax.media.jai.OpImage;
    import com.sun.media.jai.codec.SeekableStream;
    import com.sun.media.jai.codec.FileSeekableStream;
    import com.sun.media.jai.codec.TIFFDecodeParam;
    import com.sun.media.jai.codec.ImageDecoder;
    import com.sun.media.jai.codec.ImageCodec;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.imageio.ImageReadParam.*;
    class MultiPageRead extends JFrame
    ScrollingImagePanel panel;
    //     JFrame mainFrame = new JFrame();
         Container c;
         public MultiPageRead(String filename) throws IOException
    getContentPane();
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              pack();
              setTitle("Multi page TIFF Reader");
              setSize(980,1200);
              getContentPane();
    File file = new File(filename);
    SeekableStream s = new FileSeekableStream(file);
    TIFFDecodeParam param = null;
              ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
    System.out.println("Number of images in this TIFF: " + dec.getNumPages());
              ImageLayout size = new ImageLayout(,0,12,12);
    // Which of the multiple images in the TIFF file do we want to load
    // 0 refers to the first, 1 to the second and so on.
    int imageToLoad = 0;
    RenderedImage op = new NullOpImage(dec.decodeAsRenderedImage(imageToLoad), null,
    OpImage.OP_IO_BOUND,
    size);
    // Display the original in a 800x800 scrolling window
    panel = new ScrollingImagePanel(op, 100, 200);
    getContentPane().add(panel);
         public static void main(String [] args)
    String filename = args[0];
    try {System.out.println("jfdfldjfldfjldjfjldjfjdjdjdjjdjdj");
              MultiPageRead window = new MultiPageRead(filename);
                        window.pack();
                        window.show();
              catch (java.io.IOException ioe)
              System.out.println(ioe);
    regards
    jaggayya

    Changing the fonts in Print using ABAP is not possible. as basic report output is a text editor.
    By changing "Customizing of Local Layout" will only change in display screen and not in print.
    One possible way to create a new printer formatr thry SPAD and use that format in while printing.
    to know more details about SPAD
    Using SPAD - SAP Spool Administration to print different paper size
    The SAP spool system manages its own output devices. This includes mostly printers, but also fax and archiving devices. In order for you to use output devices defined in your operating system from the SAP System, you must define these devices in the SAP spool system.
    Print to a dot matrix printer using computer paper with 66 lines
    Define paper types
    Formatting process Z_60_135
    Page format DINA4
    Orientation tick both Portrait and Orientation
    Type in the comment and click save
    Device initialization
    Device type - OKI341
    Formatting process Z_60_135 then click Execute
    Double click Printer initilization
    You must key the 66 lines hexadecimals for your printer. ( line no 9)
    1 # oki341 x_paper
    2 # reset
    3 # \e\0x40
    4 # select codepage multilingual 850
    5 \e\0x52\0x1a
    6 # disable skip perforation mode
    7 \e\0x4f
    8 # select 6 lpi
    9 \e\0x32
    10 # select page length 66 lines (66=hex $42)
    11 \e\0x43\0x42
    12 # select 10 cpi font
    13 \e\0x60
    CHECK THIS LINKS
    http://help.sap.com/saphelp_nw04s/helpdata/en/df/abbb3f8e236d3fe10000000a114084/content.htm
    http://help.sap.com/saphelp_nw2004s/helpdata/en/5a/4df93bad37f87ae10000000a114084/content.htm
    http://www.geocities.com/SiliconValley/Grid/4858/sap/Basis/printprobs_solutions.htm
    Hope this helps you
    Regards
    Pavan

  • Loading large images

    Hi there,
    I'm facing lot of problem while loading large image (25+ MB JPG/TIFF) in editor pane using ImageIO. I always get OuofMemory exception or my machine (p4 2.4ghz/512 ddr) get hangs. Is there any way to load large images within a moment in Java? I have seen one s/w (written in vc++) that do the same. I'm trying to replicate that s/w.
    Is there any 3rd party Java API to do the same? Have you guys develop similar s/w before?
    I've tried many ways: by changing heap size, using ImageMagick, spliting the image, etc. but never get satisfactory results.
    Any help would be appreciated.
    Thanks in advance.
    -tamal

    You can use Java Advanced Image
    http://java.sun.com/products/java-media/jai/downloads/download-1_1_2.html
    this will avoid the out of memory error.
    I use it to read and show 20K*20K pixel images.
    the loading is immadiate.
    If you use javax.media.jai.widget.ScrollingImagePanel (deprecated) class to visulize the image is quite quick.
    Obviouse that if you want to visualize the entire image you will need to wait an approprite time for rescaling it.

  • Rendering Tiff File

    I am trying to view Tiff file, but the problem that it is not clear view
    I mean it is very bad look, not like view it in another Tiff viewer.
    and also it is too big, I mean the width and hight.
    any way, this is my code:-
    public void ReadingTiffFile()
    String strFileName = "d:\\b.tif";
    File file = new File(strFileName);
    SeekableStream s = null;
    try
    s = new FileSeekableStream(file);
    TIFFDecodeParam param = new TIFFDecodeParam();
    ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
    RenderedImage img = dec.decodeAsRenderedImage(0);
    JFrame frm = new JFrame();
    frm.getContentPane().add(new PnlTiffGraphicsView(img));
    catch (IOException ex1)
    System.out.println("Error While Rending Images");
    public class PnlTiffGraphicsView extends JPanel
    RenderedImage img = null;
    public PnlTiffGraphicsView(RenderedImage img1)
    img = img1;
    public synchronized void paintComponent(Graphics g)
    gg.drawRenderedImage(img, new AffineTransform());
    Many thanks in Advanced.

    I found this code somewhere online... I took a few snippets from it to form my own methods that accepted image paths... Hope it helps.
         import java.awt.Frame;
         import java.awt.RenderingHints;
         import java.awt.image.DataBuffer;
         import java.awt.image.renderable.ParameterBlock;
         import java.io.IOException;
         import javax.media.jai.JAI;
         import javax.media.jai.LookupTableJAI;
         import javax.media.jai.RenderedOp;
         import com.sun.media.jai.codec.FileSeekableStream;
         import com.sun.media.jai.codec.TIFFDecodeParam;
         import javax.media.jai.widget.ScrollingImagePanel;
         public class LookupSampleProgram {
             // The main method.
             public static void main(String[] args) {
         // Validate input.
         // Create an input stream from the specified file name to be
         // used with the TIFF decoder.
                 FileSeekableStream stream = null;
                 try {
                     stream = new FileSeekableStream("C:\\my.tiff");
                 } catch (IOException e) {
                     e.printStackTrace();
                     System.exit(0);
         // Store the input stream in a ParameterBlock to be sent to
         // the operation registry, and eventually to the TIFF
         // decoder.
                 ParameterBlock params = new ParameterBlock();
                 params.add(stream);
         // Specify to TIFF decoder to decode images as they are and
         // not to convert unsigned short images to byte images.
                 TIFFDecodeParam decodeParam = new TIFFDecodeParam();
                 decodeParam.setDecodePaletteAsShorts(true);
         // Create an operator to decode the TIFF file.
                 RenderedOp image1 = JAI.create("tiff", params);
         // Find out the first image's data type.
                 int dataType = image1.getSampleModel().getDataType();
                 RenderedOp image2 = null;
                 if (dataType == DataBuffer.TYPE_BYTE) {
         // Display the byte image as it is.
                     System.out.println("TIFF image is type byte.");
                     image2 = image1;
                 } else if (dataType == DataBuffer.TYPE_USHORT) {
         // Convert the unsigned short image to byte image.
                     System.out.println("TIFF image is type ushort.");
         // Setup a standard window-level lookup table. */
                     byte[] tableData = new byte[0x10000];
                     for (int i = 0; i < 0x10000; i++) {
                         tableData[i] = (byte)(i >> 8);
         // Create a LookupTableJAI object to be used with the
         // "lookup" operator.
                     LookupTableJAI table = new LookupTableJAI(tableData);
         // Create an operator to lookup image1.
                     image2 = JAI.create("lookup", image1, table);
                 } else {
                     System.out.println("TIFF image is type " + dataType +
                                        ", and will not be displayed.");
                     System.exit(0);
         // Get the width and height of image2.
                 int width = image2.getWidth();
                 int height = image2.getHeight();
         // Attach image2 to a scrolling panel to be displayed.
                 ScrollingImagePanel panel = new ScrollingImagePanel(
                                                 image2, width, height);
         // Create a frame to contain the panel.
                 Frame window = new Frame("Lookup Sample Program");
                 window.add(panel);
                 window.pack();
                 window.show();
         }-sal

  • Applet tiff viewer

    hi,
    Can any body give some sample code or idea how can display tiff image or tiff file in a web browser.
    Thanks in advanced.

    i have a code here displaying single tiff file in directory
    can i put it in an iframe of a html/jsp file?(correct me if im wrong)
    how does it done?
    import java.applet.Applet;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.renderable.ParameterBlock;
    import java.io.File;
    import java.io.FilenameFilter;
    import java.net.URL;
    import javax.media.jai.InterpolationNearest;
    import javax.media.jai.JAI;
    import javax.media.jai.PlanarImage;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JSlider;
    import javax.swing.JTextField;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import com.sun.media.jai.widget.DisplayJAI;
    * @author Sherwin_Macatangay
    public class TIFFViewer extends JFrame {
         private static final long serialVersionUID = 1L;
         String currentFile;
         private String DIRECTORY;
         private int currentPage;
         private int pageCount;
         private File F_DIRECTORY;
         private File tiff;
         private Container cPane;
         private JScrollPane display;
         private JPanel topBar;
         private JLabel unReadable;
         public JLabel pageCounter1;
         public JTextField pageCounter2;
         private JLabel pageCounter3;
         private JSlider slider;
         private DisplayJAI Dpanel;
         // private RenderedImage tiffFile;
         private PlanarImage tiffImage; // the original TIFF image
         // constructor
         public TIFFViewer() {
              // TODO Auto-generated constructor stub
         @SuppressWarnings("deprecation")
         public TIFFViewer(String directory) {
              // TODO Auto-generated constructor stub
              DIRECTORY = directory;
              F_DIRECTORY = new File(DIRECTORY);
              if (F_DIRECTORY.isDirectory()) {
                   getPageCount();// get the count of file(s) in a directory
                   for (File file : F_DIRECTORY.listFiles()) {
                        if (file.getName().toLowerCase().endsWith(".tif")) {
                             tiff = file;
                             //tiff = fileTIFF;
                             javax.swing.JOptionPane.showMessageDialog(null, "Tiff: "
                                       + tiff);
                             break;
                        }else{
                             newImage(tiff);     
                   //newImage(tiff);
                   PlanarImage image = JAI.create("fileLoad", tiff.getAbsolutePath());
                   if (image == null) {
                        System.out.println("image " + image);
                        Scale(image);
                   } else {
                        Scale(image);
                   currentPage = 1;
                   pageCounter2 = new JTextField(currentPage);
                   pageCounter3 = new JLabel("of " + pageCount);
              initViewer();
              return;
         }// end TIFFViewer()
         * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              TIFFViewer TW = new TIFFViewer();
              TW.begin("./web content/images/layout/");
         }// end main()
         public void begin(String args) {
              // We need one argument: the TIFF directory.
              if (args.length() == 0) {
                   System.err.println("Usage: java operators.TIFFViewer image");
                   javax.swing.JOptionPane.showMessageDialog(null,
                             "Usage: java operators. TIFFViewer image");
                   System.exit(0);
              new TIFFViewer(args);
         }// end begin()
         public void initViewer() {
              cPane = getContentPane();
              cPane.setLayout(new BorderLayout());
              topBar = new JPanel();
              topBar.setLayout(new FlowLayout(FlowLayout.LEADING, 0, 0));
              // setup page display and changer
              Component[] itemsToAdd = initChangerPanel();
              for (int i = 0; i < itemsToAdd.length; i++) {
                   topBar.add(itemsToAdd);
              cPane.add(topBar, BorderLayout.NORTH);
              display = new JScrollPane();
              if (tiffImage == null) {
                   unReadable = new JLabel(
                             "The file is unreadable or there's no file!");
                   display = new JScrollPane(unReadable);
              } else {
                   Dpanel = new DisplayJAI(tiffImage);
                   display = new JScrollPane(Dpanel);
              cPane.add(display, BorderLayout.CENTER);
              // pack();
              // setSize(800,700);
              setTitle(tiff.getName());
              setSize(getToolkit().getScreenSize().width, 700);
              setLocationRelativeTo(null);// center on screen
              setVisible(true);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         }// end initViewer()
         public void getPageCount() {
              FilenameFilter filter = new FilenameFilter() {
                   public boolean accept(File dir, String name) {
                        return name.toLowerCase().endsWith(".tif");
              String[] children = F_DIRECTORY.list(filter);
              pageCount = children.length;
         }// end getTIFFPageCount()
         private Component[] initChangerPanel() {
              Component[] list = new Component[10];
              // Create the start button and set icon
              /** start page */
              JButton start = new JButton();
              start.setBorderPainted(false);
              URL startImage = getClass()
                        .getResource("/winmac/gui/generic/start.gif");
              start.setIcon(new ImageIcon(startImage));
              start.setText("Start");
              start.setToolTipText("Back to start page");
              list[0] = start;
              start.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if (currentPage != 1) {
                             currentPage = 1;
                             FilenameFilter filter = new FilenameFilter() {
                                  public boolean accept(File dir, String name) {
                                       return name.toLowerCase().endsWith(".tif");
                             int i = currentPage;
                             File filename;
                             File[] startTiff = F_DIRECTORY.listFiles(filter);
                             if (i == i) {
                                  // Get filename of file
                                  filename = startTiff[i - 1];
                                  tiff = filename;
                                  newImage(tiff);
                             // set page number display
                             pageCounter2.setText(String.valueOf(currentPage));
              /** back 1 page */
              JButton back = new JButton();
              back.setBorderPainted(false);
              URL backImage = getClass().getResource("/winmac/gui/generic/back.gif");
              back.setIcon(new ImageIcon(backImage));
              back.setText("Back");
              back.setToolTipText("Back page");
              list[1] = back;
              back.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if (currentPage > 1) {
                             // currentPage -= 1;
                             currentPage--;
                             FilenameFilter filter = new FilenameFilter() {
                                  public boolean accept(File dir, String name) {
                                       return name.toLowerCase().endsWith(".tif");
                             int i = currentPage;
                             File filename;
                             File[] backTiff = F_DIRECTORY.listFiles(filter);
                             if (i == i) {
                                  // Get filename of file
                                  filename = backTiff[i - 1];
                                  tiff = filename;
                                  newImage(tiff);
                             // set page number display
                             pageCounter2.setText(String.valueOf(currentPage));
              // Create the pageCounter1, pageCounter2 and set its labels
              pageCounter1 = new JLabel("Page");
              list[2] = pageCounter1;
              list[3] = new JPanel();
              // Create the pageCounter2 and set its labels
              pageCounter2 = new JTextField(5);
              pageCounter2.setEditable(true);
              pageCounter2.setText(String.valueOf(currentPage));
              list[4] = pageCounter2;          
              /**pageCounter2.addKeyListener(new KeyAdapter(){
                   public void keyReleased(KeyEvent me){
                        FilenameFilter filter = new FilenameFilter() {
                             public boolean accept(File dir, String name) {
                                  return name.toLowerCase().endsWith(".tif");
                        int i = Integer.parseInt(pageCounter2.getText());
                        System.out.println(i);
                        File filename;                    
                        File[] getTiff = F_DIRECTORY.listFiles(filter);
                        if (i==i){
                             filename = getTiff[i-1];
                             tiff = filename;
                             newImage(tiff);
              list[5] = new JPanel();
              list[6] = pageCounter3;
              /** next one page */
              JButton next = new JButton();
              next.setBorderPainted(false);
              URL nextImage = getClass().getResource("/winmac/gui/generic/next.gif");
              next.setIcon(new ImageIcon(nextImage));
              next.setText("Next");
              next.setToolTipText("Next page");
              list[7] = next;
              next.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if (currentPage < pageCount) {
                             // currentPage += 1;
                             FilenameFilter filter = new FilenameFilter() {
                                  public boolean accept(File dir, String name) {
                                       return name.toLowerCase().endsWith(".tif");
                             int i = currentPage;
                             File filename;
                             File[] nextTiff = F_DIRECTORY.listFiles(filter);
                             if (i == currentPage) {
                                  // Get filename of file
                                  filename = nextTiff[i];
                                  tiff = filename;
                                  newImage(tiff);
                             currentPage++;
                             // set page number display
                             pageCounter2.setText(String.valueOf(currentPage));
              /** end page */
              JButton end = new JButton();
              end.setBorderPainted(false);
              URL endImage = getClass().getResource("/winmac/gui/generic/end.gif");
              end.setIcon(new ImageIcon(endImage));
              end.setText("End");
              end.setToolTipText("End page");
              list[8] = end;
              end.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if (currentPage < pageCount) {
                             currentPage = pageCount - 1;
                             FilenameFilter filter = new FilenameFilter() {
                                  public boolean accept(File dir, String name) {
                                       return name.toLowerCase().endsWith(".tif");
                             int i = currentPage;
                             File filename;
                             File[] endTiff = F_DIRECTORY.listFiles(filter);
                             if (i == currentPage) {
                                  currentPage = pageCount;
                                  // Get filename of file
                                  filename = endTiff[i];
                                  tiff = filename;
                                  newImage(tiff);
                             // set page number display
                             pageCounter2.setText(String.valueOf(currentPage));
              /** slider */
              slider = new JSlider(600, 12000, 12000);
              slider.setToolTipText("Scale image");
              list[9] = slider;
              slider.addChangeListener(new ChangeListener() {
                   public void stateChanged(ChangeEvent e) {
                        // If interactivity is off and we're still adjusting, return.
                        // Gets the scale (converting it to a percentage)
                        float scale = slider.getValue() / 12000f;
                        // Scales the original image
                        ParameterBlock pb = new ParameterBlock();
                        pb.addSource(tiffImage);                    
                        pb.add(scale);
                        pb.add(scale);
                        pb.add(0.0F);
                        pb.add(0.0F);
                        pb.add(new InterpolationNearest());
                        // Creates a new, scaled image and uses it on the DisplayJAI
                        // component
                        PlanarImage scaledImage = JAI.create("scale", pb);
                        Dpanel.set(scaledImage);
              return list;
         }// end initChangerPanel()
         public void Scale(PlanarImage image) {
              try {
                   tiffImage = image;
              } catch (Exception e) {
                   System.err.print("Scale " + e.getMessage());
         }// end Scale()
         public void newImage(File tiff) {
              // javax.swing.JOptionPane.showMessageDialog(null, "TIFF FILE:" + tiff);
              setTitle(tiff.getName());
              PlanarImage image = JAI.create("fileLoad", tiff.getAbsolutePath());
              Dpanel.set(image);
              Scale(image);
         }// end newImage()
    }// end class TIFFViewer

Maybe you are looking for