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())));
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 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 have a small requirement please help me
Firstly, I have a label, i set a icon to that label as
lbl_photo.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/images/photo.png")));
and i have a button browse to select the image.
private void btn_browseActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"jpeg, gif and png files", "jpg", "gif", "png");
int i = chooser.showOpenDialog(this);
if (i == JFileChooser.APPROVE_OPTION) {
image = chooser.getSelectedFile();
try {
BufferedImage originalImage = ImageIO.read(image);
int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
: originalImage.getType();
BufferedImage resizeImageJpg = resizeImage(originalImage, type);
photo = new ImageIcon(toImage(resizeImageJpg));
raster = resizeImageJpg.getRaster();
data = (DataBufferByte) raster.getDataBuffer();
} catch (Exception e) {
System.out.println(e.getMessage());
}
lbl_photo.setIcon(photo);
}
}
now, I am storing the selected image from browse button into database
Date date1 = new Date();
Timestamp timestamp1 = new Timestamp(date1.getTime());
String sql4 = "insert into std_photos values(?,?,?)";
pstmt5 = con.prepareStatement(sql4);
pstmt5.setInt(1, Integer.parseInt(txt_eno.getText()));
pstmt5.setString(2, "");
pstmt5.setTimestamp(3, timestamp1);
byte[] extractBytes = data.getData();
pstmt5.setBytes(2, extractBytes);
System.out.println(sql4);
image is successfully storing.but,if the user doesn't select the image through browse button the default jlabel icon should be store in the database.
please help me as early as possible
You are already checking the return value of chooser.showOpenDialog(this) for JFileChooser.APPROVE_OPTION.
In case you receive some other option or if the try-catch block reading the new image fails you could just get the old icon and write it into the database.
I know we can output an Image using Jpanel using the following code:
JFrame frame = new JFrame("IMG");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
ImageIcon image = new ImageIcon(".../img.jpg");
frame.setSize(image.getIconWidth()+10,image.getIconHeight()+35);
JLabel label1 = new JLabel(" ", image, JLabel.CENTER);
frame.getContentPane().add(label1);
frame.validate();
frame.setVisible(true);
This code would assume that I have created or already have an image file in my directory. But what I want to do is output the image in the Jpanel directly without creating the image file. How do I do that using OpenCV Mat object in JAVA?
You can convert Mat object to BufferedImage object using following method:
public static BufferedImage createAwtImage(Mat mat) {
int type = 0;
if (mat.channels() == 1) {
type = BufferedImage.TYPE_BYTE_GRAY;
} else if (mat.channels() == 3) {
type = BufferedImage.TYPE_3BYTE_BGR;
} else {
return null;
}
BufferedImage image = new BufferedImage(mat.width(), mat.height(), type);
WritableRaster raster = image.getRaster();
DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
byte[] data = dataBuffer.getData();
mat.get(0, 0, data);
return image;
}
Then you can simply display image using ImageIcon:
// Load image using Highgui or create Mat object other way you want
Mat mat = Highgui.imread(".../img.jpg");
ImageIcon image = new ImageIcon(createAwtImage(mat));
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