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();
Related
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){
}
I have a program here in java and MySQL for database. However the problem is: when the data for IMAGE in the SQL is null, the program stops loading picture.
It shows "java.lang.IllegalArgumentException: input == null!". My question is how will I able to set the Icon picture as null and continue.
try{
PreparedStatement ps = conn.prepareStatement(President);
ResultSet rs = ps.executeQuery();
if(rs.next()){
rs.absolute(1);
FirstName1.setText(rs.getString("cFirstname"));
LastName1.setText(rs.getString("CLastname"));
MiddleName1.setText(rs.getString("cmiddlename"));
BufferedImage im1 = ImageIO.read(rs.getBinaryStream("cimage"));
ImageIcon image1 = new ImageIcon(im1);
Image img1 = image1.getImage();
Image newImage = img1.getScaledInstance(144, 144, Image.SCALE_SMOOTH);
ImageIcon after = new ImageIcon(newImage);
btnPic1.setIcon(after);
btnPic1.setText("");
FirstName1.setVisible(true);
LastName1.setVisible(true);
btnPic1.setVisible(true);
MiddleName1.setVisible(true);
}
In my data the image stored here is null.
if(rs.next()){
rs.absolute(2);
FirstName2.setText(rs.getString("cFirstname"));
LastName2.setText(rs.getString("CLastname"));
MiddleName2.setText(rs.getString("cmiddlename"));
BufferedImage im2 = ImageIO.read(rs.getBinaryStream("cimage"));
ImageIcon image2 = new ImageIcon(im2);
Image img2 = image2.getImage();
Image newImage2 = img2.getScaledInstance(144, 144, Image.SCALE_SMOOTH);
ImageIcon after2 = new ImageIcon(newImage2);
btnPic2.setIcon(after2);
btnPic2.setText("");
FirstName2.setVisible(true);
LastName2.setVisible(true);
btnPic2.setVisible(true);
MiddleName2.setVisible(true);
}
Then my program doesn't do this and onwards.
if(rs.next()){
rs.absolute(3);
FirstName3.setText(rs.getString("cFirstname"));
LastName3.setText(rs.getString("CLastname"));
MiddleName3.setText(rs.getString("cmiddlename"));
BufferedImage im3 = ImageIO.read(rs.getBinaryStream("cimage"));
ImageIcon image3 = new ImageIcon(im3);
Image img3 = image3.getImage();
Image newImage3 = img3.getScaledInstance(144, 144, Image.SCALE_SMOOTH);
ImageIcon after3 = new ImageIcon(newImage3);
btnPic3.setIcon(after3);
btnPic3.setText("");
FirstName3.setVisible(true);
LastName3.setVisible(true);
btnPic3.setVisible(true);
MiddleName3.setVisible(true);
}
Which line throws the IllegalArgumentException? Perhaps I'm being over-simplistic, but a simple solution could be that you check for a null image variable immediately before this line, and if the variable is null, don't use it, and skip that line(s). A better solution is to find out why the images are null and to prevent this from happening in the first place.
The result code would be something like this
if(rs.next()){
rs.absolute(2);
FirstName2.setText(rs.getString("cFirstname"));
LastName2.setText(rs.getString("CLastname"));
MiddleName2.setText(rs.getString("cmiddlename"));
if(rs.getBinaryStream("cimage")!=null){
BufferedImage im2 = ImageIO.read(rs.getBinaryStream("cimage"));
ImageIcon image2 = new ImageIcon(im2);
Image img2 = image2.getImage();
Image newImage2 = img2.getScaledInstance(144, 144, Image.SCALE_SMOOTH);
ImageIcon after2 = new ImageIcon(newImage2);
btnPic2.setIcon(after2);
btnPic2.setText("");}
else{
btnPic2.setText("No Picture");
}
FirstName2.setVisible(true);
LastName2.setVisible(true);
btnPic2.setVisible(true);
MiddleName2.setVisible(true);
}
Adding a "if null" statement. Although in this use. I reverse it. Thank you for the comments and answers. I have been able to come up with this solution.
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.
I have a problem with showing a picture from the database, the database saves the picture in blob, when i pick up the data the blob passes to Byte[], so after that i do that to show the image, why didnt work?
Select_1 xp = new Select_1();
byte[] img=xp.Select_1(username);
InputStream in = new ByteArrayInputStream(img);
BufferedImage image = ImageIO.read(in);
BufferedImage resizedImage=resize(image,204,204);
ImageIcon icon=new ImageIcon(resizedImage);
lblavatar.setIcon(icon);
Edit according to the comment:
Originally, the image was written using the following methods:
blob = (Blob) connect.createBlob();
ImageIcon ii = new ImageIcon(ficheiro);
ObjectOutputStream oos;
oos = new ObjectOutputStream(blob.setBinaryStream(1));
oos.writeObject(ii);
oos.close();
psInsert.setBlob(4, blob);
You are not serialzing a BufferedImage, but an ImageIcon.
In order to create an image from the blob data, you have to do "the opposite" of what you have been doing to create the blob. In this case, you'll have to do something along the lines of
byte[] img=xp.Select_1(username);
InputStream in = new ByteArrayInputStream(img);
ObjectInputStream ois = new ObjectInputStream(in);
ImageIcon imageIcon = (ImageIcon)ois.readObject();
Now, you have an ImageIcon, from which you can obtain the Image. For many cases, this image can be used directly. If you really need a BufferedImage, then you can do
BufferedImage bi = new BufferedImage(204,204,BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.drawImage(imageIcon.getImage(), 0, 0, 204, 204, null);
g.dispose();
Then the buffered image will contain your image (already scaled to the desired target size of 204,204 in this case).
In any case, you should consider to not store the image as a serialized ImageIcon. Instead, you should write your image into a byte array as a PNG or JPG file, and store the resulting byte array as the blob in the database, as, for example, shown in Java: BufferedImage to byte array and back
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();