I am trying to retrieve blob data type from database table and display the image in a imageView. Here is my select SQL statement:
public boolean retrieve(){
boolean success = false;
ResultSet rs = null;
DBController db = new DBController();
db.getConnection();
String dbQuery = "SELECT * FROM sm_product WHERE productName ='" + name +"'";
rs = db.readRequest(dbQuery);
try {
if(rs.next()){
desc = rs.getString("productDescription");
price = rs.getInt("productPrice");
quantity = rs.getInt("productQuantity");
dateStr = rs.getString("dateOfCreation");
category = rs.getString("productCategory");
Blob blob = rs.getBlob("productImage");
byte[] data = blob.getBytes(0, (int) blob.length());
image = ImageIO.read(new ByteArrayInputStream(data)); //Error here
success = true;
}
}
catch(Exception e){
e.printStackTrace();
}
db.terminate();
return success;
}
After retrieved, I want to display it in a imageview. Here is the code:
panel.getMyImageView().setImage(product.getImage());
However, I got incompatible type error message. I know image = ImageIO.read(new ByteArrayInputStream(data)); this line supposed to store as BufferedImage and then from there I slowly convert to image datatype and display in image view. But after 2 hours of researching, I got no luck. Can somebody please help me with it?
Thanks in advance.
Toolkit.getDefaultToolkit().createImage(data)
Call this for the byte array read from the blob
Related
I've read many articles and tutorials but still have not found a solution. I also read in some posts that are on stackoverflow but still have not found a solution. everything I ask for help to solve my problem. Thank you earlier. sorry for my English is garbled
try {
int baris = tabelpelanggan.getSelectedRow();
stt = K.PrepareStatement();
rs = stt.executeQuery("select image from pelanggan where idpelanggan='"
+ tabelpelanggan.getValueAt(baris, 0).toString() + "'");
byte[] imagee = null;
while (rs.next()) {
Blob blob = rs.getBlob("image");
imagee = blob.getBytes(1, (int) blob.length());
}
Image i = Toolkit.getDefaultToolkit().createImage(imagee);
ImageIcon ii = new ImageIcon(i);
Image iii = ii.getImage();
Image newicon = iii.getScaledInstance(labelImage.getWidth(), labelImage.getHeight(), Image.SCALE_SMOOTH);
ImageIcon icon = new ImageIcon(newicon);
labelImage.setIcon(icon);
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
I'm using the next code to show image in label , to set nothing to label when picture column is null :
ResultSet rset2 = stmnt.executeQuery("select Picture from Pictures where Client_ID_pass =1" );
while(rset2.next()){
byte[] Passimg = rset2.getBytes("Picture");
//Resize The ImageIcon
ImageIcon Passimage = new ImageIcon(Passimg);
Image Passim = Passimage.getImage();
Image PassmyImg = Passim.getScaledInstance(PassLBL.getWidth(), PassLBL.getHeight(),Image.SCALE_SMOOTH);
ImageIcon newPassImage = new ImageIcon(PassmyImg);
PassLBL.setIcon(newPassImage);
if(Passimg.length < 0){
PassLBL.settext("No Picture");
PassLBL.setIcon(null);
}
}
I've tried the next :
if(Passimg.equals(null)
{PassLBL.settext("No Picture");}
and tried
if(Passimg == null)
{PassLBL.settext("No Picture"); }
but didn't work !
when you retrive the data from the resultSet
byte[] Passimg = rset2.getBytes("Picture");
put if statement there
if(passimg == null) {
label.setText("nothing")
lable.setIcon(null);//to remove the old picture
}else {
//show the image like you did before
lable.setText("");
icon=create your icon here
lable.setIcon(icon);
}
i didn't undertand what you need exactly hope this help you
I am trying to load an image which is in a MySQL database as blob data format ([B#e96bf) but I can't load it to a JLabel as shown below. It shows the ByteArrayInputStream is empty.
byte[] bytesl = null;
ResultSet rs = DB.DB.search("select image from imageio where id = '2'");
while (rs.next()) {
bytesl = rs.getBytes(1);
}
BufferedImage imag = ImageIO.read(new ByteArrayInputStream(bytesl));
Image img = imag;
img = img.getScaledInstance(jLabel1.getWidth(), jLabel1.getHeight(),
Image.SCALE_SMOOTH);
jLabel2.setIcon(new ImageIcon(img));
I think you code doesn't go to while loop, because there's no records with such query. Most probably issue is the ' signs around 2. Usually id is a number, but in your request it looks like you compare it to string. Try to remove apostrophe signs around 2.
fileContent = Files.readAllBytes(f2.toPath());
DB.DB.statement("insert into imageio (image) values ('" + fileContent + "')");
You've just inserted the string [B#96bf into the database. ImageIO can't turn that into an image, so it returns null.
You should at least use a PreparedStatement and provide the data as an argument. You should really be using a Blob and an input stream here.
I'm trying to display images retrieve from MySQL database of blob datatype. Could not figure out what is the problem that causes the image column to display data like this [B#29b8e4f7 instead of image icon.
DefaultTableModel model = new DefaultTableModel(new Object[]{
"image", "item_name", "quantity","price", "category", "color", "size"}, 0){
#Override
public Class<?> getColumnClass(int column) {
switch(column){
case 0: return ImageIcon.class;
default: return String.class;
}
}
};
myTable.setModel(model);
...
ResultSet rs = database.getRS();
int columns = rs.getMetaData().getColumnCount();
while(rs.next()){
Object[] row = new Object[columns];
for(int i = 1; i <= columns; i++){
row[i-1] = rs.getObject(i);
}
DefaultTableModel defmodel = (DefaultTableModel) tableItem.getModel();
defmodel.insertRow(rs.getRow()-1, row);
}
Since you used preparedstatement.setBlob(1, InputStream); to store the image, I have to assume that you stored the physical image file/format and not just the pixel data.
You need to read back this image format and convert to a supported image format for Swing/Java.
Start by getting a Blob reference to the database field...
Blob blob = rs.getBlob(1);
Once you have a Blob, you can use it's binary InputStream and read the data...
BufferedImage image = null;
try (InputStream is = blob.getBinaryStream()) {
image = ImageIO.read(is);
} catch (IOException exp) {
exp.printStackTrace();
}
Now, you can make it an ImageIcon using new ImageIcon(image) and put this within your table model...
I have a blob type field in my MySQL, I want to put the data in this field in JLabel as Icon. For example this JLabel will be user's Profile Picture in my form.
I used this codes but nothing happens
and also I want to fix to width or fix any image size in my jlabel
DefaultTableModel pic = MyDB.DataTable("SELECT `Picture` FROM `photo` WHERE `Employee ID` = 'EQ0103'");
if (pic.getRowCount() > 0){
Blob blob = pic.getBlob(1);
byte[] image1 = blob.getBytes(1, ALLBITS);
ImageIcon image = new ImageIcon(image1);
picture.setIcon(image);
getContentPane().add(picture);
setVisible(true);
}
picture is the name of my jlabel
First : Return the Input stream from your database :
String query = "SELECT `Picture` FROM `photo` WHERE `Employee ID` = 'EQ0103'";
stmt = (PreparedStatement) con.prepareStatement(query);
ResultSet result = stmt.executeQuery();
Returned image from Database
BufferedImage im = ImageIO.read(result.getBinaryStream(1));
Then make rezise to this image :
im =linearResizeBi(im, /*width*/, /*height*/);
linearResizeBi Method :
static public BufferedImage linearResizeBi(BufferedImage origin, int width, int height) {
BufferedImage resizedImage = new BufferedImage(width, height ,BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
float xScale = (float)width / origin.getWidth();
float yScale = (float)height / origin.getHeight();
AffineTransform at = AffineTransform.getScaleInstance(xScale,yScale);
g.drawRenderedImage(origin,at);
g.dispose();
return resizedImage;
}
then make the image is an Icon:
ImageIcon image1 = new ImageIcon(im);
then add the Icon to The Jlabel :
picture.setIcon(image);
getContentPane().add(picture);
setVisible(true);
Use a resultset
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT `Picture` FROM `photo` WHERE `Employee ID` = 'EQ0103'");
You may change from
Blob blob = rs.getBlob(1);
to another altenative of
InputStream binaryStream = rs.getBinaryStream(1);
You can refer to the official guide of getting image from a blog here
http://docs.oracle.com/javase/1.5.0/docs/guide/jdbc/blob.html
I got
my filename should be like this
txtPicPath.setText(file.getAbsoluteFile().toString());
and i used these codes, and also it fits with the jlabel size
ResultSet rst = MyDB.rsFetch("SELECT `Picture` FROM `photo` WHERE `Employee ID` = '"+ Data.User.getText()+"'");
while (rst.next()) {
Blob filenameBlob = rst.getBlob("Picture");
byte[] content = filenameBlob.getBytes(1L,(int)filenameBlob.length());
ImageIcon ik = new ImageIcon(content);
Image img = ik.getImage();
Image newimg = img.getScaledInstance(Data.picture.getWidth(), Data.picture.getHeight(), java.awt.Image.SCALE_SMOOTH);
ik = new ImageIcon(newimg);
Data.picture.setIcon(ik);
}
Blob has a getBinaryStream() which returns a stream of bytes containing the data stored in the blob.
ImageIcon, which implements Icon, has a constructor which takes a byte array as argument.
JLabel has a setIcon(Icon) method.
label.setIcon(new ImageIcon(ByteStreams.toByteArray(blob.getBinaryStream())));
Try:
picture.setIcon(new ImageIcon(ByteStreams.toByteArray(blob.getBinaryStream())));