irsbenz
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
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
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();
The last snippet comes from this link:
http://srikanthtechnologies.com/blog/java/fileupload.aspx
http://srikanthtechnologies.com/blog/java/fileupload.aspx
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)
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 ();
...
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
http://java-x.blogspot.com/2007/01/handling-oracle-large-objects-with-jdbc.html
ASKER
Hi,
While I converting the .tiff file to .png I getting the error.
The java Code is shown below.
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;
}
}
What kind of error ?
ASKER
The below the following error when I compile.
Project: C:\JDeveloper\mywork\Appli cation1\fi le\file.jp r
C:\JDeveloper\mywork\Appli cation1\fi le\src\fil e\Class1.j ava
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
Project: C:\JDeveloper\mywork\Appli
C:\JDeveloper\mywork\Appli
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.
This line does not make sense:
RenderedImage readMultiPageTiff("c:\temp
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.
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.
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();
}
};
}
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 ?
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_c ore.jar and
JDK_HOME/jre/lib/ext/jai_c odec.jar
after that this code made a conversion for me:
I attach original .tif and converted .png so that you could use them to try
applet.TIF
applet.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_c
JDK_HOME/jre/lib/ext/jai_c
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);
I attach original .tif and converted .png so that you could use them to try
applet.TIF
applet.png
ASKER
Hi,
Thanks for the reply. where I can add you code in my above code.
Please reply me.
Thanks
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
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();
}
};
}
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.
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;
}
}
}
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(ActionEven t evt) {
Connection conn = null;
String imageId;
imageId = txtfileno.getText();
String fileName;
fileName = txtfileno.getText();
fileName= fileName.substring(0,fileN ame.lastIn dexOf(".") );
fileName = fileName+".png";
try {
conn = getConnection();
if (!fileName.equals("")) {
PreparedStatement ps = conn.prepareStatement("INS ERT 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("INS ERT INTO IMAGES VALUES (?, empty_blob())");
ps.setString(1, imageId);
ps.execute();
ps.close();
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
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(ActionEven
Connection conn = null;
String imageId;
imageId = txtfileno.getText();
String fileName;
fileName = txtfileno.getText();
fileName= fileName.substring(0,fileN
fileName = fileName+".png";
try {
conn = getConnection();
if (!fileName.equals("")) {
PreparedStatement ps = conn.prepareStatement("INS
ps.setString(1, imageId);
FileInputStream fis = new FileInputStream(fileName);
ps.setBinaryStream(2, fis, fis.available());
ps.execute();
ps.close();
} else {
PreparedStatement ps = conn.prepareStatement("INS
ps.setString(1, imageId);
ps.execute();
ps.close();
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
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,
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.
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.
ASKER
When I click the upload it's give me the follwoing error.
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOf BoundsExce ption: String index out of range: -1
at java.lang.String.substring (String.ja va:1937)
at client.gui1$insertBlobActi on.actionP erformed(g ui1.java:1 60)
at javax.swing.AbstractButton .fireActio nPerformed (AbstractB utton.java :1995)
at javax.swing.AbstractButton $Handler.a ctionPerfo rmed(Abstr actButton. java:2318)
at javax.swing.DefaultButtonM odel.fireA ctionPerfo rmed(Defau ltButtonMo del.java:3 87)
at javax.swing.DefaultButtonM odel.setPr essed(Defa ultButtonM odel.java: 242)
at javax.swing.plaf.basic.Bas icButtonLi stener.mou seReleased (BasicButt onListener .java:236)
at java.awt.Component.process MouseEvent (Component .java:6267 )
at javax.swing.JComponent.pro cessMouseE vent(JComp onent.java :3267)
at java.awt.Component.process Event(Comp onent.java :6032)
at java.awt.Container.process Event(Cont ainer.java :2041)
at java.awt.Component.dispatc hEventImpl (Component .java:4630 )
at java.awt.Container.dispatc hEventImpl (Container .java:2099 )
at java.awt.Component.dispatc hEvent(Com ponent.jav a:4460)
at java.awt.LightweightDispat cher.retar getMouseEv ent(Contai ner.java:4 577)
at java.awt.LightweightDispat cher.proce ssMouseEve nt(Contain er.java:42 38)
at java.awt.LightweightDispat cher.dispa tchEvent(C ontainer.j ava:4168)
at java.awt.Container.dispatc hEventImpl (Container .java:2085 )
at java.awt.Window.dispatchEv entImpl(Wi ndow.java: 2478)
at java.awt.Component.dispatc hEvent(Com ponent.jav a:4460)
at java.awt.EventQueue.dispat chEvent(Ev entQueue.j ava:599)
at java.awt.EventDispatchThre ad.pumpOne EventForFi lters(Even tDispatchT hread.java :269)
at java.awt.EventDispatchThre ad.pumpEve ntsForFilt er(EventDi spatchThre ad.java:18 4)
at java.awt.EventDispatchThre ad.pumpEve ntsForHier archy(Even tDispatchT hread.java :174)
at java.awt.EventDispatchThre ad.pumpEve nts(EventD ispatchThr ead.java:1 69)
at java.awt.EventDispatchThre ad.pumpEve nts(EventD ispatchThr ead.java:1 61)
at java.awt.EventDispatchThre ad.run(Eve ntDispatch Thread.jav a:122)
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOf
at java.lang.String.substring
at client.gui1$insertBlobActi
at javax.swing.AbstractButton
at javax.swing.AbstractButton
at javax.swing.DefaultButtonM
at javax.swing.DefaultButtonM
at javax.swing.plaf.basic.Bas
at java.awt.Component.process
at javax.swing.JComponent.pro
at java.awt.Component.process
at java.awt.Container.process
at java.awt.Component.dispatc
at java.awt.Container.dispatc
at java.awt.Component.dispatc
at java.awt.LightweightDispat
at java.awt.LightweightDispat
at java.awt.LightweightDispat
at java.awt.Container.dispatc
at java.awt.Window.dispatchEv
at java.awt.Component.dispatc
at java.awt.EventQueue.dispat
at java.awt.EventDispatchThre
at java.awt.EventDispatchThre
at java.awt.EventDispatchThre
at java.awt.EventDispatchThre
at java.awt.EventDispatchThre
at java.awt.EventDispatchThre
looks like the error is in this line:
fileName= fileName.substring(0,fileN ame.lastIn dexOf(".") );
Print the name of the file immedaitely after this:
fileName = txtfileno.getText();
System.out.println(fileNam e);
fileName= fileName.substring(0,fileN
Print the name of the file immedaitely after this:
fileName = txtfileno.getText();
System.out.println(fileNam
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("filena me: " + fileName);
fileName= fileName.substring(0,fileN ame.lastIn dexOf(".") );
fileName = fileName+".png";
You are not
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("filena
fileName= fileName.substring(0,fileN
fileName = fileName+".png";
You are not
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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("filena me: " + fileName);
fileName= fileName.substring(0,fileN ame.lastIn dexOf(".") );
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.
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("filena
fileName= fileName.substring(0,fileN
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();
btnUpload.setEnabled(false
befre
Connection conn = null;
and
btnUpload.setEnabled(true)
aftre conn.close();
ASKER
Excellent and straight to point and quick feedbcak.
http://stackoverflow.com/questions/2291358/how-do-i-convert-a-tif-to-png-in-java