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.
Related
I am converting excel (xls, xlsx) file to html. But when image is there I am not able to get image size(dimention) which is there in the excel file. I am using apache poi.
How to get image size of that file? Please help me on that.
This source explains how to get picture data from the excel file: http://poi.apache.org/spreadsheet/quick-guide.html#Images.
Within the loop there is a
byte[] data = pict.getData();
You can use that byte array, write it to a ByteArrayOutputStream object and call the size() method to retrieve the size of the file written to the outputstream.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(data);
int fileSizeInBytes = baos.size();
I hope this helps.
This may be an overkill, but you can create an image from the byte array and check its size. For example:
for (HSSFPictureData pic : workbook.getAllPictures()) {
InputStream in = new ByteArrayInputStream(pic.getData());
BufferedImage image = ImageIO.read(in);
System.out.println(image.getWidth() + ":" + image.getHeight());
}
How do i get byte[] from javafx image/imageview class? I want to store my image as a Blob into my database.This is the method that i use for it
public PreparedStatement prepareQuery(HSQLDBConnector connector) {
try {
Blob logoBlob = connector.connection.createBlob();
logoBlob.setBytes(0,logo.getImage());//stuck here
for (int i = 0, a = 1; i < data.length; i++, a++) {
connector.prepStatCreateProfile.setString(a, data[i]);
}
//store LOB
connector.prepStatCreateProfile.setBlob(11, logoBlob);
} catch (SQLException ex) {
ex.printStackTrace();
}
return connector.prepStatCreateProfile;
}
Is there a way to convert from my current object (imageview),image) into byte[]?, or shoud i start to think about using other class for my image/ alternatively point to the location with reference and work with paths/urls?
try this one:
BufferedImage bImage = SwingFXUtils.fromFXImage(logo.getImage(), null);
ByteArrayOutputStream s = new ByteArrayOutputStream();
ImageIO.write(bImage, "png", s);
byte[] res = s.toByteArray();
s.close(); //especially if you are using a different output stream.
should work depending on the logo class
you need to specify a format while writing and reading, and as far as I remember bmp is not supported so you will end up with a png byte array on the database
pure java fx solution trace ( == you will have to fill in missing points :)
Image i = logo.getImage();
PixelReader pr = i.getPixelReader();
PixelFormat f = pr.getPixelFormat();
WriteablePixelFromat wf = f.getIntArgbInstance(); //???
int[] buffer = new int[size as desumed from the format f, should be i.width*i.height*4];
pr.getPixels(int 0, int 0, int i.width, i.height, wf, buffer, 0, 0);
Lorenzo's answer is correct, this answer just examines efficiency and portability aspects.
Depending on the image type and storage requirements, it may be efficient to convert the image to a compressed format for storage, for example:
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
ImageIO.write(SwingFXUtils.fromFXImage(fxImage, null), "png", byteOutput);
Blob logoBlob = connector.connection.createBlob();
logoBlob.setBytes(0, byteOutput.toByteArray());
Another advantage of doing a conversion to a common format like png before persisting the image is that other programs which deal with the database would be able to read the image without trying to convert it from a JavaFX specific byte array storage format.
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
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())));
I am given a byte[] array in Java which contains the bytes for an image, and I need to output it into an image. How would I go about doing this?
Much thanks
BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
If you know the type of image and only want to generate a file, there's no need to get a BufferedImage instance. Just write the bytes to a file with the correct extension.
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(path))) {
out.write(bytes);
}
From Database.
Blob blob = resultSet.getBlob("pictureBlob");
byte [] data = blob.getBytes( 1, ( int ) blob.length() );
BufferedImage img = null;
try {
img = ImageIO.read(new ByteArrayInputStream(data));
} catch (IOException e) {
e.printStackTrace();
}
drawPicture(img); // void drawPicture(Image img);
Since it sounds like you already know what format the byte[] array is in (e.g. RGB, ARGB, BGR etc.) you might be able to use BufferedImage.setRGB(...), or a combination of BufferedImage.getRaster() and WritableRaster.setPixels(...) or WritableRaster.setSamples(...). Unforunately both of these methods require you transform your byte[] into one of int[], float[] or double[] depending on the image format.
According to the Java docs, it looks like you need to use the MemoryImageSource Class to put your byte array into an object in memory, and then use Component.createImage(ImageProducer) next (passing in your MemoryImageSource, which implements ImageProducer).