Why is this java code unable to save image in mysql database? - java

I have passed BufferedImage as argument from jsp to java with following code:
<%BufferedImage citizen = ImageIO.read(new File(add1));%>
<%BufferedImage degree=ImageIO.read(new File(deg1));%>
<%String available=com.Package1.UpdataStudentInfo.useValues(citizen, degree);%>
Here "add1" and "deg1" are the path of images.
In java page, I have written following code so that I could update those Image to database (Here, I had no image saved in db column previously, so I wanted to update those columns with no images). I have kept name of variables same in argument; i.e. BufferedImage citizen of jsp is BufferedImage citizen in java and BufferedImage degree of jsp is BufferedImage degree in java as well. So there is no problem in variable name.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
try{
ByteArrayOutputStream os1 = new ByteArrayOutputStream();
ImageIO.write(citizen, "PNG", os1);
ByteArrayInputStream citizen_is = new ByteArrayInputStream(os1.toByteArray());
ByteArrayOutputStream os2 = new ByteArrayOutputStream();
ImageIO.write(degree, "PNG", os2);
ByteArrayInputStream degree_is = new ByteArrayInputStream(os2.toByteArray());
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/crm","root","");
PreparedStatement stmt=con.prepareStatement("UPDATE student SET citizenship=?, degree=? WHERE sn=? ");
stmt.setBlob(1, (Blob) citizen_is);
stmt.setBlob(2, (Blob) degree_is);
stmt.setInt(3, p);
int x=stmt.executeUpdate();
con.close();
}
I have catch statement as well to handle exception. But there is no any exception, no any runtime error and compile time error. But the image is not getting stored in the database.
Please, help me to store these two image in mysql database.

String updateSQL = "UPDATE student SET citizenship=?, degree=? WHERE sn=? ";
File os1 = new File(filenameImageCitizenShip); //load image as file
File os2 = new File(filenameImageDegree); //load image as file
FileInputStream inputOs1 = new FileInputStream(os1);
FileInputStream inputOs2 = new FIleInputStream(os2);
try{
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/crm","root","");
PreparedStatement pstmt = conn.prepareStatement(updateSQL);
pstmt.setBinaryStream(1,os1);
pstmt.setBinaryStream(2,os2);
pstmt.setBinaryStream(3,p);
pstmt.executeUpdate();
}catch(Exception e){
}

Related

Inserting an image blob into MySQL - NullPointerException

I'm working on a database application in which I'm inserting images into a database. I'm storing the InputStreams in the database as a BLOB, and I am having issues retrieving them and setting them to an ImageIcon.
try{
// Return a resultset That contains
// the photos from the hashtags the user is following.
preparedStatement = conn.prepareStatement("SELECT * FROM PHOTOS WHERE CARID=?");
preparedStatement.setInt(1, 1);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
newPhoto = new Photo(resultSet.getInt(1), resultSet.getInt(2),
resultSet.getLong(3), resultSet.getBinaryStream(4));
System.out.println(resultSet.getBinaryStream(4));
photos.add(newPhoto);
System.out.println("Retrieving a photo");
}
}
photos is an ArrayList using my Photo class, which I am returning. Every time I try to display the images, I am getting the following error...
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at business.appdev.Home.paintEditFrame(Home.java:577)
which is coming from the following code..
editImageLabel[i].setIcon(
new ImageIcon(img.getScaledInstance(imageSize, imageSize, imageSize)));
I have some basic println commands that are showing me what's returning from the MySQL database, which is
java.io.ByteArrayInputStream#2c0213a5
Retrieving a photo
java.io.ByteArrayInputStream#252ab7be
Retrieving a photo
where img is a BufferedImage. Any help would be greatly appreciated, Thanks!
Code for handling of the InputStream returned from the resultSet
for(int i = 0; i < photos.size(); i++){
img = ImageIO.read(photos.get(i).getInputStream());
editImageLabel[i] = new JLabel("");
editImageLabel[i].setIcon(new ImageIcon(img.getScaledInstance(imageSize, imageSize, imageSize)));
updated Photo class with byte[] data
Based on some other posts I've read, I'm storing the byte[] into a varbinary in MySQL. After that, I grab the photo data from my database using
InputStream in = resultSet.getBinaryStream(4);
byte[] photoData = new byte[(int) resultSet.getLong(3)];
ByteArrayOutputStream os = new ByteArrayOutputStream();
for (int len; (len = in.read(photoData)) != -1;)
os.write(photoData, 0, len);
os.flush();
I then create my photo object and return an ArrayList of photos. This has eliminated the NullPointerException, but I now cannot get the ImageIcon JLabels to show up. I use the following code to add them to a JPanel,
InputStream in = new ByteArrayInputStream(photos.get(i).getData());
BufferedImage newImage = ImageIO.read(in);
editImageLabel[i] = new JLabel("");
editImageLabel[i].setIcon(new ImageIcon(newImage.getScaledInstance(imageSize, imageSize, Image.SCALE_DEFAULT)));
and then I place the Label onto the JPanel.
Avoid the trouble of encoding and decoding images by storing the image in the filesystem and just the path to the image in your database. This can help to keep your database size down which, in turn, can help your transactional efficiency. You can write up some quick code to make a numeric filename for the file on your server.

Saving an Image on Data Base

Basically I have to save an image I put on a JLabel on my DB(I have a BLOB var there)
JLabel LImg = new JLabel();
ImageIcon img = new ImageIcon("**filepath**");
LImg.setIcon(img);
stmt.executeUpdate("INSERT INTO CLIENT(ID, IMAGE) VALUES (1,"+LImg.getIcon()+")");
After running a few tests, I found out the getIcon method returns the file path, which explains this error
GDS Exception. 335544569. Dynamic SQL Error
SQL error code = -104
Token unknown - line 1, column 132
:
Please, be especific on your answer(I'm new on JAVA)
You cannot paste the image itself into a SQL statement. You need to use a parameterized prepared statement, and set the value being inserted as a byte array:
BufferedImage bi = (BufferedImage)LImg.getImage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, type, baos);
byte[] dataToWrite = baos.toByteArray();
PreparedStatement stmt = con.prepareStatement("INSERT INTO CLIENT(ID, IMAGE) VALUES (1,?)");
stmt.setBlob(1, dataToWrite);
stmt.executeUpdate();

Image storing in sql server database using java

I am trying to save Image at SQL-SERVER Database using procedures .I have a PROCEDURE name with input parameters but I don't have procedure syntax.
BufferedImage imm = ImageIO.read(new File("C:\\MY DATA\\Release 2\\18.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(imm, "jpg", baos );
baos.flush();
byte[] immAsBytes = baos.toByteArray();
baos.close();
con.setAutoCommit(true);
CallableStatement statement = con.prepareCall(query);
ByteArrayInputStream baisForIndex2 = new ByteArrayInputStream(immAsBytes);
ByteArrayInputStream baisForIndex3 = new ByteArrayInputStream(immAsBytes);
statement.setDate(1, sqlDate);
statement.setBinaryStream(2, baisForIndex2, immAsBytes.length);
statement.setBinaryStream(3, baisForIndex3, immAsBytes.length);
statement.executeUpdate();
Error msg: Operand type clash: nvarchar is incompatible with image.
SQLSTATE: S0002
Error code: 206
Error code: 0
What I want is compatible type of Java with IMAGE type of DB of sql-server.
When inserting a stream into a blob, the JDBC driver will read the specified length from it and will not reset the the stream when done.
In your example, you use this stream for placeholder 2, and then again for placeholder 3 and specify the entire length of the underlying byte[] each time. This way, when the driver gets to placeholder 3, the stream is exhausted, and cannot be read.
One solution could be to use two stream objects:
CallableStatement statement = con.prepareCall(query);
ByteArrayInputStream baisForIndex2 = new ByteArrayInputStream(immAsBytes);
ByteArrayInputStream baisForIndex3 = new ByteArrayInputStream(immAsBytes);
statement.setDate(1, sqlDate);
statement.setBinaryStream(2, baisForIndex2, immAsBytes.length);
statement.setBinaryStream(3, baisForIndex3, immAsBytes.length);
statement.executeUpdate();

Save image inside specific folder and store path in mysql to display later

For my project, I am creating an expense management system. There is a place where the user can select an image file from local disk and add it as an attachment when adding a new expense.
The uploaded image should be displayed in a jLabel and then should be saved inside the project folder (say for e.g. /src/accounts/media) when clicking the save button, and the path should be saved inside a varchar column in mysql database for later retrieval.
For now, I can upload the image and display the image in jLabel.
Can anyone help me out on how save that image file inside a folder and to store the path in database?
JFileChooser chooser = new JFileChooser();
FileFilter ft = new FileNameExtensionFilter("Image Files", "jpg", "png", "jpeg");
//FileFilter ft2 = new FileNameExtensionFilter("PDF Files", "pdf");
chooser.addChoosableFileFilter(ft);
//chooser.addChoosableFileFilter(ft2);
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
filePath = f.getAbsolutePath().toString();
BufferedImage img = null;
try {
img = ImageIO.read(new File(filePath));
} catch (IOException e) {
e.printStackTrace();
}
Image dimg = img.getScaledInstance(lblAttachment.getWidth(), lblAttachment.getHeight(), Image.SCALE_SMOOTH);
ImageIcon icon = new ImageIcon(dimg);
lblAttachment.setText("");
lblAttachment.setIcon(icon);
To copy file to another location, you can choose any
Way1
Way2
To store the path, make a file-path column write insert query (SQL) :
prepareStatement ps = conn.prepareStatement("INSERT INTO filePath VALUES(?, ?, ?)" );
ps.setString(1,filePath);
ps.set..
// conn, connection object
Full tutorial Here
Edit:
To save it in you some default Resources folder, You can obtain path, for EG:
public class ClassDemo {
public static void main(String[] args) throws Exception {
ClassDemo c = new ClassDemo();
Class cls = c.getClass();
// finds resource relative to the class location
URL url = cls.getResource("file.txt");
System.out.println("Value = " + url);
// finds resource relative to the class location
url = cls.getResource("newfolder/a.txt");
System.out.println("Value = " + url);
}
}

How to convert CLOB to image or vice versa?

In Oracle 11g I have a table that has a CLOB column containing image data for each row.
I need to convert the CLOB field back to an image. I searched a bit through google but I could not find a working example.
Can anyone help please?
Thank you
I found the solution. This is what I used
public void convertFromClob(Clob c, File f2) {
try {
InputStream inStream = c.getAsciiStream();
StringWriter sw = new StringWriter();
IOUtils.copy(inStream, sw);
// Transfer the data
byte[] data = Base64.decodeBase64(sw.toString());
BufferedImage image = ImageIO.read(new ByteArrayInputStream(data));
ImageIO.write(image, "png", f2);
} catch (Exception e) {
e.printStackTrace();
}
}
You can call directly the above method passing as parameters your Clob variable and the File to store the image. Tung

Categories