Link to home
Start Free TrialLog in
Avatar of irsbenz
irsbenzFlag for Canada

asked on

Converting .tiff file to .png file and then insert it into database using java.

Hi,
I need to convert .tiff file to .png file and then insert that file into the Oracle database using java.
Can any body help me out to resolve this as I new to Java.
Thanks
Avatar of for_yan
for_yan
Flag of United States of America image

This is how to insert as BLOB:

   Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr");
            con.setAutoCommit(false);

            PreparedStatement ps = con.prepareStatement("insert into photos values(?,?,?)");
            ps.setString(1, photoid);
            ps.setString(2, phototitle);
            // size must be converted to int otherwise it results in error
            ps.setBinaryStream(3, file.getInputStream(), (int) file.getSize());
            ps.executeUpdate();
            con.commit();
            con.close();

Open in new window

Avatar of irsbenz

ASKER

thanks for the reply, but can I insert it into a table in oracle database.
yes, the last two postings are about inserting into oracle
type
insert file as BLOB into Oracle JDBC
in google and you'll see many good examples.

Thsi is one of them:
(it of course does not matter is it .png or gif or any other file)

PreparedStatement pstmt = conn.prepareStatement ("INSERT INTO t1 VALUES (?,?)");
pstmt.setInt (1, 100);
File fBlob = new File ( "image1.gif" );
FileInputStream is = new FileInputStream ( fBlob );
pstmt.setBinaryStream (2, is, (int) fBlob.length() );
pstmt.execute ();
...

Open in new window

This is also a good example of inserting BLOB into and reading BLOB from Oracle table:
http://java-x.blogspot.com/2007/01/handling-oracle-large-objects-with-jdbc.html
Avatar of irsbenz

ASKER

Hi,
While I converting the .tiff file to .png I getting the error.

The java Code is shown below.

package file;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class Class1 {
    public Class1() {
        super();
        RenderedImage readMultiPageTiff("c:\temp\2.tiff");
    }
    public static void readMultiPageTiff(String *fileName*)throws IOException{
           File file = new File(fileName);
           SeekableStream seekableStream = new FileSeekableStream(file);
           ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", seekableStream, null);
           int numPages = decoder.getNumPages();
           RenderedImage image[]= new RenderedImage[numPages];
           int count = 0;
           for(int i=0;i<decoder.getNumPages();i++){
               image[i] = decoder.decodeAsRenderedImage(i);
               count++;
           }
           String newFolderName;
           String s3 = fileName;
           String [] temp = null;
           temp = s3.split("\\.");
           int j;
                    j = 0;
                     do{
                              newFolderName = temp[j];
                              String spoonFeeding = newFolderName;
                              File f = new File(spoonFeeding);
                              f.mkdirs();
                              j++;
                     }while (j<1);      
           for (int i = 0; i < count; i++) {
               RenderedImage page = decoder.decodeAsRenderedImage(i);
               File fileObj = new File(newFolderName+"/" + (i+1) + ".png");
               System.out.println("Saving " + fileObj.getCanonicalPath());
               ParameterBlock parBlock = new ParameterBlock();
               parBlock.addSource(page);
               parBlock.add(fileObj.toString());
               parBlock.add("png");
               RenderedOp renderedOp = JAI.create("filestore",parBlock);
               renderedOp.dispose();
           }
           return image;
        }
}

Open in new window

What kind of error ?
Avatar of irsbenz

ASKER

The below the following error when I compile.
Project: C:\JDeveloper\mywork\Application1\file\file.jpr
C:\JDeveloper\mywork\Application1\file\src\file\Class1.java
Error(16,49):  <identifier> expected
Error(16,51):  ';' expected
Error(16,59):  illegal start of type
Error(16,60):  <identifier> expected
Error(16,61):  ';' expected
Error(16,79):  <identifier> expected
Error(23,12):  illegal start of type
Error(23,21):  ')' expected
Error(23,22):  illegal start of type
Error(23,23):  <identifier> expected
Error(23,24):  ';' expected
Error(23,33):  > expected
Error(23,49):  <identifier> expected
Error(23,51):  illegal start of type
Error(23,52):  <identifier> expected
Error(23,53):  ';' expected
Error(24,21):  illegal start of type
Error(24,23):  ';' expected
Error(24,56):  <identifier> expected
Error(24,58):  <identifier> expected
Error(25,21):  <identifier> expected
Error(28,12):  class, interface, or enum expected
Error(29,12):  class, interface, or enum expected
Error(30,12):  class, interface, or enum expected
Error(31,12):  class, interface, or enum expected
Error(33,12):  class, interface, or enum expected
Error(34,21):  class, interface, or enum expected
Error(35,22):  class, interface, or enum expected
Error(37,31):  class, interface, or enum expected
Error(38,31):  class, interface, or enum expected
Error(39,31):  class, interface, or enum expected
Error(40,31):  class, interface, or enum expected
Error(41,22):  class, interface, or enum expected
Error(43,12):  class, interface, or enum expected
Error(43,28):  class, interface, or enum expected
Error(43,39):  class, interface, or enum expected
Error(45,16):  class, interface, or enum expected
Error(46,16):  class, interface, or enum expected
Error(47,16):  class, interface, or enum expected
Error(48,16):  class, interface, or enum expected
Error(49,16):  class, interface, or enum expected
Error(50,16):  class, interface, or enum expected
Error(51,16):  class, interface, or enum expected
Error(52,16):  class, interface, or enum expected
Error(53,12):  class, interface, or enum expected
Error(55,9):  class, interface, or enum expected
Error(18,12):  cannot find class SeekableStream
Error(19,12):  cannot find class ImageDecoder
Error(23,48):  cannot find class i
Error(24,57):  cannot find class i
Error(24,34):  package decoder does not exist
Error(25,16):  cannot find class count
Error(16,25):  missing method body, or declare abstract
Error(17,33):  cannot find variable fileName
Error(18,48):  cannot find class FileSeekableStream
Error(19,35):  cannot find variable ImageCodec
Error(23,34):  missing method body, or declare abstract
well, you code does not comply with Java syntax



This line does not make sense:

 RenderedImage readMultiPageTiff("c:\temp\2.tiff");


No sense to have super() in constructor if your class does not
subclass anything but Object


This has some asterisks
String *fileName*
which are not allowed in variable names


when I corrected some obvious stuff  - it complained about not finding some classes
like SeekableStream etc.



Where did you get this code?

Why do you need it,
Why would not you use simple code suggested in the first link which I posted above:

public static void main(final String[] args) throws Exception
{
    final BufferedImage tif = ImageIO.read(new File("test.tif"));
    ImageIO.write(tif, "png", new File("test.png"));
}


And you need to follow some Java synatx ruules, etc.
Avatar of irsbenz

ASKER

Hi,
Thanks for your reply, actually I am new to java, I am developing application which convert the .tiff file to .png.
The scenario is the user will select the file by click the button which open the Open File dialog which select the file and then its convert the file from .tiff to .png and then insert that converted file into the Oracle database. I have written the code for the above scenario but for converting the file from .tiff to .png  and insert into the database are left. I am forwarding the code below please have a look on it.
import java.lang.Class;
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import java.io.File;
import java.io.IOException;

import javax.swing.*;
import org.im4java.core.ConvertCmd;
import org.im4java.core.IMOperation;
import java.util.*;

import org.im4java.core.IM4JavaException;
//Main class
public class gui1{
 //Declare variables
 static JFrame frame1;
 static Container pane;
 static JButton btnConnect, btnBrowse, btnUpload;
 static JLabel lblfileno, lblFilename, lblTitle;
 static JTextField txtfileno, txtFilename;
 static Insets insets;

 public static void main (String args[]){
  //Set Look and Feel
  try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
  catch (ClassNotFoundException e) {}
  catch (InstantiationException e) {}
  catch (IllegalAccessException e) {}
  catch (UnsupportedLookAndFeelException e) {}

  //Create the frame
  frame1 = new JFrame ("Sample GUI Application");
  frame1.setSize (600,300);
  pane = frame1.getContentPane();
  insets = pane.getInsets();
  pane.setLayout (null);
     
     String filename = File.separator+"tmp";
     JFileChooser fc = new JFileChooser(new File(filename));


  //Create controls
  btnConnect = new JButton ("Convert File");
  btnBrowse = new JButton ("Browse");
  btnUpload = new JButton ("Upload");
  lblfileno = new JLabel ("File #:");
  lblFilename = new JLabel ("File Name:");
  lblTitle = new JLabel ("Sample Demo");
  txtfileno = new JTextField (30);
  txtFilename = new JTextField (50);
  
     
  //Add all components to panel
  pane.add (lblfileno);
  pane.add (lblFilename);
  pane.add (lblTitle);
   pane.add (txtfileno);
   pane.add (txtFilename);
  pane.add (btnConnect);
  pane.add (btnBrowse);
  pane.add (btnUpload);
  //Place all components
  
  lblTitle.setBounds (insets.left + 250,  insets.top + 35, lblTitle.getPreferredSize().width +10, lblTitle.getPreferredSize().height +10);
  lblFilename.setBounds (insets.left + 27,  insets.top + 75, lblFilename.getPreferredSize().width, lblFilename.getPreferredSize().height);
  txtFilename.setBounds (lblFilename.getX() + lblFilename.getWidth() + 5, insets.top + 75, txtFilename.getPreferredSize().width, txtFilename.getPreferredSize().height);
  btnBrowse.setBounds (txtFilename.getX() + txtFilename.getWidth() + 5, insets.top + 75, btnBrowse.getPreferredSize().width, btnBrowse.getPreferredSize().height);
  lblfileno.setBounds (insets.left + 27, insets.top + 100, lblfileno.getPreferredSize().width, lblfileno.getPreferredSize().height);
  txtfileno.setBounds (lblfileno.getX() + lblfileno.getWidth() + 25, insets.top + 100, txtfileno.getPreferredSize().width, txtfileno.getPreferredSize().height);
  btnConnect.setBounds (insets.left + 150,  insets.top  + 155, btnConnect.getPreferredSize().width, btnConnect.getPreferredSize().height);
  btnUpload.setBounds (insets.left + 250,  insets.top  + 155, btnUpload.getPreferredSize().width, btnUpload.getPreferredSize().height);
  frame1.setVisible (true);
  btnBrowse.addActionListener(new OpenFileAction(frame1, fc));
  
   
  }

 public static class btnConnectAction implements ActionListener{
  public void actionPerformed (ActionEvent e){
   System.out.println("You entered "+txtFilename.getText());
  }
 }
    public  static class OpenFileAction extends AbstractAction {
        JFrame frame;
        JFileChooser chooser;

        OpenFileAction(JFrame frame, JFileChooser chooser) {
            super("Open...");
            this.chooser = chooser;
            this.frame = frame;
        }

        public void actionPerformed(ActionEvent evt) {
            // Show dialog; this method does not return until dialog is closed
            chooser.showOpenDialog(frame);

            // Get the selected file
            File file = chooser.getSelectedFile();
            txtFilename.setText(file.getAbsolutePath());//+"/"+file.getName()); 
        }
    };

    // This action creates and shows a modal save-file dialog.
    public class SaveFileAction extends AbstractAction {
        JFileChooser chooser;
        JFrame frame;

        SaveFileAction(JFrame frame, JFileChooser chooser) {
            super("Save As...");
            this.chooser = chooser;
            this.frame = frame;
        }

        public void actionPerformed(ActionEvent evt) {
            // Show dialog; this method does not return until dialog is closed
            chooser.showSaveDialog(frame);

            // Get the selected file
            File file = chooser.getSelectedFile();
            
          
        }
    };
   } 

Open in new window

I guess you need to install JAI I/O tools to do the conversion:

 

http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-java-client-419417.html#jaiio-1.0_01-oth-JPR

Have you installed it ?
OK. I just successfully converted my tiff to png.
so you go here:
http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-java-client-419417.html#jai-1_1_2_01-oth-JPR


assuming you are on windows 32-bit and you have Java JDK installed on your machine
you download version called Windows JDK Install, file which ends with windows-i586-jdk.exe

then you execute this file - it will ask you about location of your JDK - it usually will pick it up itself

Then you make sure that the CLASSPATH of your project contains
two jars

JDK_HOME/jre/lib/ext/jai_core.jar and

JDK_HOME/jre/lib/ext/jai_codec.jar

after that this code made a conversion for me:

          String source = "applet.tif";
FileOutputStream out = new FileOutputStream ("applet.png");
RenderedOp src = JAI.create("fileload", source);
            PNGImageEncoder encoder = new PNGImageEncoder(out, null);
encoder.encode (src);

Open in new window


I attach original .tif and converted .png so that you could use them to try
applet.TIF
applet.png
Avatar of irsbenz

ASKER

Hi,
Thanks for the reply. where I can add you code in my above code.
Please reply me.
Thanks
I'm not sure this code is connected to
the issue of converting tif to png,
but anyway - in the code below user will
browse to the TIF file and it will check if the selected file has a tif or tiff extension and
if it has, then it would convert it to the file with .png extension in the same folder.

You can then store this png file to database using one of the links
which I posted in the beginning

import com.sun.media.jai.codecimpl.PNGImageEncoder;

import java.io.FileOutputStream;
import java.lang.Class;
import java.sql.*;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import java.io.File;
import java.io.IOException;

import javax.swing.*;
//import org.im4java.core.ConvertCmd;
//import org.im4java.core.IMOperation;
import java.util.*;

//import org.im4java.core.IM4JavaException;
//Main class
public class gui1{
 //Declare variables
 static JFrame frame1;
 static Container pane;
 static JButton btnConnect, btnBrowse, btnUpload;
 static JLabel lblfileno, lblFilename, lblTitle;
 static JTextField txtfileno, txtFilename;
 static Insets insets;

 public static void main (String args[]){
  //Set Look and Feel
  try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
  catch (ClassNotFoundException e) {}
  catch (InstantiationException e) {}
  catch (IllegalAccessException e) {}
  catch (UnsupportedLookAndFeelException e) {}

  //Create the frame
  frame1 = new JFrame ("Sample GUI Application");
  frame1.setSize (600,300);
  pane = frame1.getContentPane();
  insets = pane.getInsets();
  pane.setLayout (null);

     String filename = File.separator+"tmp";
     JFileChooser fc = new JFileChooser(new File(filename));


  //Create controls
  btnConnect = new JButton ("Convert File");
  btnBrowse = new JButton ("Browse");
  btnUpload = new JButton ("Upload");
  lblfileno = new JLabel ("File #:");
  lblFilename = new JLabel ("File Name:");
  lblTitle = new JLabel ("Sample Demo");
  txtfileno = new JTextField (30);
  txtFilename = new JTextField (50);


  //Add all components to panel
  pane.add (lblfileno);
  pane.add (lblFilename);
  pane.add (lblTitle);
   pane.add (txtfileno);
   pane.add (txtFilename);
  pane.add (btnConnect);
  pane.add (btnBrowse);
  pane.add (btnUpload);
  //Place all components

  lblTitle.setBounds (insets.left + 250,  insets.top + 35, lblTitle.getPreferredSize().width +10, lblTitle.getPreferredSize().height +10);
  lblFilename.setBounds (insets.left + 27,  insets.top + 75, lblFilename.getPreferredSize().width, lblFilename.getPreferredSize().height);
  txtFilename.setBounds (lblFilename.getX() + lblFilename.getWidth() + 5, insets.top + 75, txtFilename.getPreferredSize().width, txtFilename.getPreferredSize().height);
  btnBrowse.setBounds (txtFilename.getX() + txtFilename.getWidth() + 5, insets.top + 75, btnBrowse.getPreferredSize().width, btnBrowse.getPreferredSize().height);
  lblfileno.setBounds (insets.left + 27, insets.top + 100, lblfileno.getPreferredSize().width, lblfileno.getPreferredSize().height);
  txtfileno.setBounds (lblfileno.getX() + lblfileno.getWidth() + 25, insets.top + 100, txtfileno.getPreferredSize().width, txtfileno.getPreferredSize().height);
  btnConnect.setBounds (insets.left + 150,  insets.top  + 155, btnConnect.getPreferredSize().width, btnConnect.getPreferredSize().height);
  btnUpload.setBounds (insets.left + 250,  insets.top  + 155, btnUpload.getPreferredSize().width, btnUpload.getPreferredSize().height);
  frame1.setVisible (true);
  btnBrowse.addActionListener(new OpenFileAction(frame1, fc));


  }

 public static class btnConnectAction implements ActionListener{
  public void actionPerformed (ActionEvent e){
   System.out.println("You entered "+txtFilename.getText());
     


  }
 }
    public  static class OpenFileAction extends AbstractAction {
        JFrame frame;
        JFileChooser chooser;

        OpenFileAction(JFrame frame, JFileChooser chooser) {
            super("Open...");
            this.chooser = chooser;
            this.frame = frame;
        }

        public void actionPerformed(ActionEvent evt) {
            // Show dialog; this method does not return until dialog is closed
            chooser.showOpenDialog(frame);

            // Get the selected file
            File file = chooser.getSelectedFile();
            txtFilename.setText(file.getAbsolutePath());//+"/"+file.getName());
            
                       String tifFile = file.getAbsolutePath();

             if(!tifFile.toUpperCase().endsWith("TIF") && !tifFile.toUpperCase().endsWith("TIFF")) {
          System.out.println("wrong file name !");
          return;

      }

     String root = tifFile.substring(0,tifFile.lastIndexOf("."));

       System.out.println(root + ".png");

      System.out.println(tifFile);
        


                   try{
      FileOutputStream out = new FileOutputStream(root + ".png");
RenderedOp src = JAI.create("fileload", tifFile);
            PNGImageEncoder encoder = new PNGImageEncoder(out, null);
encoder.encode (src);
                   }catch(Exception ex){
                       ex.printStackTrace();
                   }





        }
    };

    // This action creates and shows a modal save-file dialog.
    public class SaveFileAction extends AbstractAction {
        JFileChooser chooser;
        JFrame frame;

        SaveFileAction(JFrame frame, JFileChooser chooser) {
            super("Save As...");
            this.chooser = chooser;
            this.frame = frame;
        }

        public void actionPerformed(ActionEvent evt) {
            // Show dialog; this method does not return until dialog is closed
            chooser.showSaveDialog(frame);

            // Get the selected file
            File file = chooser.getSelectedFile();


        }
    };
   }

Open in new window

Avatar of irsbenz

ASKER

Hi,
Thanks for your help, I can able to convert the .tiff file to .png file but I am trying to insert into the database it's not inserting and no error have popup. The below code compile successfully.
package client;


import com.sun.media.jai.codecimpl.PNGImageEncoder;
import com.sun.media.jai.codecimpl.PNGImageEncoder;
import java.io.FileOutputStream;
import java.lang.Class;
import java.sql.*;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import javax.swing.*;
import java.util.*;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

//Main class
public class gui1{
 //Declare variables
 static JFrame frame1;
 static Container pane;
 static JButton btnConnect, btnBrowse, btnUpload;
 static JLabel lblfileno, lblFilename, lblTitle;
 static JTextField txtfileno, txtFilename;
 static Insets insets;

 public static void main (String args[]){
  //Set Look and Feel
  try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
  catch (ClassNotFoundException e) {}
  catch (InstantiationException e) {}
  catch (IllegalAccessException e) {}
  catch (UnsupportedLookAndFeelException e) {}

  //Create the frame
  frame1 = new JFrame ("Conversion Application");
  frame1.setSize (600,300);
  pane = frame1.getContentPane();
  insets = pane.getInsets();
  pane.setLayout (null);
  String filename = File.separator+"tmp";
  JFileChooser fc = new JFileChooser(new File(filename));


  //Create controls
  btnConnect = new JButton ("Convert File");
  btnBrowse = new JButton ("Browse");
  btnUpload = new JButton ("Upload");
  lblfileno = new JLabel ("File #:");
  lblFilename = new JLabel ("File Name:");
  lblTitle = new JLabel ("Convert Tiff File To Png");
  txtfileno = new JTextField (50);
  txtFilename = new JTextField (50);


  //Add all components to panel
  pane.add (lblfileno);
  pane.add (lblFilename);
  pane.add (lblTitle);
  pane.add (txtfileno);
   pane.add (txtFilename);
  pane.add (btnConnect);
  pane.add (btnBrowse);
  pane.add (btnUpload);
  //Place all components

  lblTitle.setBounds (insets.left + 210,  insets.top + 35, lblTitle.getPreferredSize().width +10, lblTitle.getPreferredSize().height +10);
  lblFilename.setBounds (insets.left + 27,  insets.top + 75, lblFilename.getPreferredSize().width, lblFilename.getPreferredSize().height);
  txtFilename.setBounds (lblFilename.getX() + lblFilename.getWidth() + 5, insets.top + 75, txtFilename.getPreferredSize().width, txtFilename.getPreferredSize().height);
  btnBrowse.setBounds (txtFilename.getX() + txtFilename.getWidth() + 5, insets.top + 75, btnBrowse.getPreferredSize().width, btnBrowse.getPreferredSize().height);
  lblfileno.setBounds (insets.left + 27, insets.top + 100, lblfileno.getPreferredSize().width, lblfileno.getPreferredSize().height);
  txtfileno.setBounds (lblfileno.getX() + lblfileno.getWidth() + 25, insets.top + 100, txtfileno.getPreferredSize().width, txtfileno.getPreferredSize().height);
  btnConnect.setBounds (insets.left + 150,  insets.top  + 155, btnConnect.getPreferredSize().width, btnConnect.getPreferredSize().height);
  btnUpload.setBounds (insets.left + 250,  insets.top  + 155, btnUpload.getPreferredSize().width, btnUpload.getPreferredSize().height);
  frame1.setVisible (true);
  frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  btnBrowse.addActionListener(new OpenFileAction(frame1, fc));
  btnConnect.addActionListener(new btnConnectAction(frame1));
  btnUpload.addActionListener(new insertBlobAction(frame1));        
        }

 public static class btnConnectAction extends AbstractAction { //implements ActionListener{
        //public void actionPerformed (ActionEvent e){
        JFrame frame;

        btnConnectAction(JFrame frame) 
        {
           
        }

        /**
         * @param e
         */
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            String kip;
            kip = txtFilename.getText();
            String rt;
            rt = kip.substring(0,kip.lastIndexOf("."));
           //JOptionPane.showMessageDialog(frame1, rt+ ".png");
            try{
                FileOutputStream out = new FileOutputStream(rt + ".png");
                RenderedOp src = JAI.create("fileload", kip);
                PNGImageEncoder encoder = new PNGImageEncoder(out, null);
                encoder.encode (src);
              }catch(Exception ex){
                ex.printStackTrace();
                }
            JOptionPane.showMessageDialog(frame1, "File Converted Successfully");
         }
 }
    public  static class OpenFileAction extends AbstractAction {
        JFrame frame;
        JFileChooser chooser;
        OpenFileAction(JFrame frame, JFileChooser chooser) {
            super("Open...");
            this.chooser = chooser;
            this.frame = frame;
            }

        public void actionPerformed(ActionEvent evt) {
            // Show dialog; this method does not return until dialog is closed
            chooser.showOpenDialog(frame);
            // Get the selected file
            File file = chooser.getSelectedFile();
            txtFilename.setText(file.getAbsolutePath());//+"/"+file.getName());
            String tifFile = file.getAbsolutePath();
        if(!tifFile.toUpperCase().endsWith("TIF") && !tifFile.toUpperCase().endsWith("TIFF")) {
          JOptionPane.showMessageDialog(frame1,"wrong file name !");
          return;
        }
     String root = tifFile.substring(0,tifFile.lastIndexOf("."));
          }
    };



    private static class insertBlobAction extends AbstractAction{
        private insertBlobAction(JFrame p0) {
        }
      public void actionPerformed(ActionEvent evt) {
        Connection conn = null;
        String imageId;
           imageId = txtfileno.getText();
         String  fileName;
           fileName = txtfileno.getText();
         fileName=  fileName.substring(0,fileName.lastIndexOf("."));
           fileName = fileName+".png";
           try {
             conn = getConnection();
             if (!fileName.equals("")) {
               PreparedStatement ps = conn.prepareStatement("INSERT INTO IMAGES VALUES(?, ?)");
               ps.setString(1, imageId);
               FileInputStream fis = new FileInputStream(fileName);
               ps.setBinaryStream(2, fis, fis.available());
               ps.execute();
               ps.close();
             } else {
               PreparedStatement ps = conn.prepareStatement("INSERT INTO IMAGES VALUES (?, empty_blob())");
               ps.setString(1, imageId);
               ps.execute();
               ps.close();
             }
             conn.close();
           } catch (Exception e) {
             e.printStackTrace();
           }
         }
         public void readBlob(String fileName) {
           Connection conn = null;
           try {
             conn = getConnection();
             Statement st = conn.createStatement();
             ResultSet rs = st.executeQuery("SELECT IMAGE FROM IMAGES");
             while (rs.next()) {
                // The following two lines can be replaced by
                // InputStream is = rs.getBinaryStream(1);
               Blob blob = rs.getBlob(1);
               InputStream is = blob.getBinaryStream();
               FileOutputStream fos = null;
               fos = new FileOutputStream(fileName);
               byte[] data = new byte[1024];
               int i = 0;
               while ((i = is.read(data)) != -1) {
                 fos.write(data, 0, i);
               }
             }
             conn.close();
           } catch (Exception e) {
             e.printStackTrace();
           }
         }
         public void writeBlob(String fileName) {
           Connection conn = null;
           try {
             conn = getConnection();
             Statement st = conn.createStatement();
             ResultSet rs = st.executeQuery("SELECT IMAGE FROM IMAGES FOR UPDATE");
             while (rs.next()) {
               Blob blob = rs.getBlob(1);
               System.out.println(blob);
                OutputStream os = blob.setBinaryStream(1);
               FileInputStream fis = null;
               fis = new FileInputStream( fileName);
               byte[] data = new byte[1];
               int i;
               while ((i = fis.read(data)) != -1) {
                 os.write(data, 0, i);
               }
               os.close();
               break;
             }
             conn.close();
           } catch (Exception e) {
             e.printStackTrace();
           }
         }
         private Connection getConnection() throws ClassNotFoundException, SQLException {
           Class.forName("oracle.jdbc.driver.OracleDriver");
           Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1528:demo", "scott", "tiger");
           return conn;
         }
       
    }
}

Open in new window

Add System.out.println()
several times within this method - you have very complex calling of events -
if there is no error perhoas it does not go there - put severla printouts we'll have more information


 public void actionPerformed(ActionEvent evt) {
        Connection conn = null;
        String imageId;
           imageId = txtfileno.getText();
         String  fileName;
           fileName = txtfileno.getText();
         fileName=  fileName.substring(0,fileName.lastIndexOf("."));
           fileName = fileName+".png";
           try {
             conn = getConnection();
             if (!fileName.equals("")) {
               PreparedStatement ps = conn.prepareStatement("INSERT INTO IMAGES VALUES(?, ?)");
               ps.setString(1, imageId);
               FileInputStream fis = new FileInputStream(fileName);
               ps.setBinaryStream(2, fis, fis.available());
               ps.execute();
               ps.close();
             } else {
               PreparedStatement ps = conn.prepareStatement("INSERT INTO IMAGES VALUES (?, empty_blob())");
               ps.setString(1, imageId);
               ps.execute();
               ps.close();
             }
             conn.close();
           } catch (Exception e) {
             e.printStackTrace();
           }
         }
Avatar of irsbenz

ASKER

Thanks for the reply, I will try to System.out.println() and revert you back.
Is there  any simple solution for this insert into database you can guide me.

Thanks,
This is a simple solution - it should work.
You have to my mind too convoluted system of handling events,
and you don't see any error, so I suspect it just does not get executed,
but as to storing in the blob this is quite normal way.
Avatar of irsbenz

ASKER

When I click the upload it's give me the follwoing error.
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
      at java.lang.String.substring(String.java:1937)
      at client.gui1$insertBlobAction.actionPerformed(gui1.java:160)
      at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
      at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
      at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
      at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
      at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
      at java.awt.Component.processMouseEvent(Component.java:6267)
      at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
      at java.awt.Component.processEvent(Component.java:6032)
      at java.awt.Container.processEvent(Container.java:2041)
      at java.awt.Component.dispatchEventImpl(Component.java:4630)
      at java.awt.Container.dispatchEventImpl(Container.java:2099)
      at java.awt.Component.dispatchEvent(Component.java:4460)
      at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
      at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
      at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
      at java.awt.Container.dispatchEventImpl(Container.java:2085)
      at java.awt.Window.dispatchEventImpl(Window.java:2478)
      at java.awt.Component.dispatchEvent(Component.java:4460)
      at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
      at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
      at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
      at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
looks like the error is in this line:
fileName=  fileName.substring(0,fileName.lastIndexOf("."));

Print the name of the file immedaitely after this:
   fileName = txtfileno.getText();
System.out.println(fileName);
Avatar of irsbenz

ASKER

Even though I put message there and run the code and then click to upload button it's given me the same error.
What did it print?
Of course message will not change the error
Look at what it prints as fileName - it should print it before the error
- you are nit getting filename form the textfiiled correctly - that is most probably the point


String imageId;
           imageId = txtfileno.getText();
         String  fileName;
           fileName = txtfileno.getText();
   Ssytem.out.println("filename: " + fileName);
         fileName=  fileName.substring(0,fileName.lastIndexOf("."));
           fileName = fileName+".png";

You are not
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of irsbenz

ASKER

Thanks very much,
I got it actually I giving the txtfileno instead of txtfilename.
String imageId;
           imageId = txtfileno.getText();
         String  fileName;
           //fileName = txtfileno.getText();
           //fileName = txtfilename.getText();
   Ssytem.out.println("filename: " + fileName);
         fileName=  fileName.substring(0,fileName.lastIndexOf("."));
           fileName = fileName+".png";

Now its running perfect. Once again thanks very much.
One more thing I like to know if we want to disable the upload button and it's enable once the file converted successfully and again disable when the record is successfully inserted.
Can you help me on this.
add

btnUpload.setEnabled(false);

befre

Connection conn = null;

and

btnUpload.setEnabled(true);

aftre conn.close();
Avatar of irsbenz

ASKER

Excellent and straight to point and quick feedbcak.