I am trying to convert a byte array to a bufferedImage to display in a jLabel but the ImageIO.read() property is returning a null value and therefore a NullPonterException. What should I do?
InputStream input = new ByteArrayInputStream(array);
try {
BufferedImage bufer = ImageIO.read(input);
ImageIcon icon=new ImageIcon(new ImageIcon(bufer).getImage().getScaledInstance(jLabel3.getWidth(), jLabel3.getHeight(), Image.SCALE_SMOOTH));
jLabel3.setIcon(icon);
} catch (IOException ex) {
Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
}`
According to the javadoc, the read(InputStream) method ...
"Returns a BufferedImage as the result of decoding a supplied InputStream with an ImageReader chosen automatically from among those currently registered. The InputStream is wrapped in an ImageInputStream. If no registered ImageReader claims to be able to read the resulting stream, null is returned."
It is most likely that the last sentence explains your problem.
What should I do?
So your approach to solving this would be:
Check that the contents of array is what you expect it to be.
Determine what kind of image format it is, and that it is correctly represented. For example, if the image was stored in a database or sent in a network request, make sure that it hasn't gotten mangled in the process.
Check that it is a supported image format; i.e. one that there should be a registered ImageReader class for.
Thanks for helping me to solve the problem I going to post the response here to help other.
1.The queries to the database (postgresql) must be preparedStatement because if you are saving an image converted to byte [] this declaration gives you a setBinaryStream functionality and when you retrieve it and add it in a byte[] nothing changes
////This way save the image and his path (the last is optional)
JFileChooser f = new JFileChooser();
f.showOpenDialog(null);
File file = f.getSelectedFile();
FileInputStream s = null;
String path = file.getAbsolutePath();
try {
s = new FileInputStream(file);
Conexion();
PreparedStatement pq = conexion.prepareStatement("INSERT INTO prueba(foto, cam) VALUES (?, ?);");
pq.setBinaryStream(1, s, (int) file.length());
pq.setString(2, path);
pq.executeUpdate();
s.close();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
}
/////This way retrive the info
byte[] array = null;
String photopath = "";
try {
Conexion();
PreparedStatement p = conexion.prepareStatement("SELECT foto, cam FROM prueba;");
ResultSet sq = p.executeQuery();
while (sq.next()) {
array = sq.getBytes("foto");
photopath = sq.getString("cam");
//jLabel3.setIcon(new ImageIcon(array));
break;
}
sq.close();
p.close();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
}
ImageIcon icon=new ImageIcon(array);
Related
I am retrieving gif images from Wolfram|Alpha. In an effort to minimize queries I want to store those images and only query W|A when the data is changed, so I am storing the images as a bytea data type in my postgres db. The "save" portion seems to be working because there is data. System.out.println(rs.getString("fnPlotImg")) yields this: \x4275666665726564496d6167654035356437373834323a2074797065203d203120446972656374436f6c6f724d6f64656c3a20726d61736b3d66663030303020676d61736b3d6666303020626d61736b3d666620616d61736b3d3020496e7465676572496e7465726c65617665645261737465723a207769647468203d2032303020686569676874203d20313335202342616e6473203d203320784f6666203d203020794f6666203d203020646174614f66667365745b305d2030
I have been able to successfully update the image from W|A using this bit of code:
String path = ((WAImage) element).getURL();
URL url = new URL(path);
BufferedImage image = ImageIO.read(url);
picLabel.setIcon(new ImageIcon(image));
I would like to update my application with the image from the database and have attempted this code:
byte[] ba = rs.getBytes("fnPlotImg");
try{
picLabel.setIcon(new ImageIcon(ba));
} catch (NullPointerException e) {
e.printStackTrace();
}
My rationale is that bytea is a byte array, getBytes() is supposed to retrieve a byte array, and ImageIcon() is supposed to handle a byte array.However, if I don't build in a null pointer exception it errors out. I presume this is because I am not saving the image to DB correctly or I am not retrieving it correctly.
All thoughts are welcome, I'm getting fatigued so I'll check in the morning with fresh eyes.
I don't have a installation of PostgreSQL available, but I think you should be writing/reading the image format and not the BufferedImage data.
For example, writing might look something like...
Connection con = ...;
BufferedImage img = ...;
try (PreparedStatement stmt = con.prepareStatement("insert into tableofimages (image) values (?)")) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
ImageIO.write(img, "png", baos);
try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) {
stmt.setBinaryStream(1, bais);
int rows = stmt.executeUpdate();
System.out.println(rows + " rows updated");
}
}
} catch (SQLException | IOException exp) {
exp.printStackTrace();
}
And reading might look something like...
Connection con = ...;
try (PreparedStatement stmt = con.prepareStatement("select image from tableofimages")) {
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
try (InputStream is = rs.getBinaryStream(1)) {
BufferedImage img = ImageIO.read(is);
}
}
}
} catch (SQLException | IOException exp) {
exp.printStackTrace();
}
I'am getting a problem whene i execute upadate query , the problem is whene i wante to update the blob column im my sqlite table, i notice that only the path this blob file are stored. but whene is use insert query with binding value like that :pst.setBinaryStream(File); it works fine!
I get my blob file with this code :
File image=null;
URL photoURL = null;
try {
photoURL = new URL(addadh_adherent_photo_label.getText());
} catch (MalformedURLException ex) {
Logger.getLogger(ParametresController.class.getName()).log(Level.SEVERE, null, ex);
}
try {
image= new File( URLDecoder.decode( photoURL.getFile(), "UTF-8" ) );
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(ParametresController.class.getName()).log(Level.SEVERE, null, ex);
}
FileInputStream fis = null;
try {
fis = new FileInputStream(image);
} catch (FileNotFoundException ex) {
Logger.getLogger(ParametresController.class.getName()).log(Level.SEVERE, null, ex);
}
and here is my update query :
int AderentId =100;
String updateAderent=" UPDATE gss_aderent SET"
+ "ad_photo='"+image+"'
+ "WHERE ad_id='"+AderentId+"' ";
stmt.executeUpdate(updateAderent);
My problem is : The updated value isn't a blob value but just his path:( my question is how to store(update) blob value in update query ? does exist a method to bind BinaryStream parametre for update query ? can i use preparedStatement in update query ?
Your application looks like it's open to SQL Injection attacks
Use a PreparedStatement and setBlob(int x, InputStream in)
I created an application that uses JSON for the database, and it seems to write fine, and the file reader reads the database fine, but I cant seem to get the database values from the database value.
here is my parsing code:
String userEnteredString = UserEntered.getText();
String userHomeLocal = Tutschedule.userHome;
Reader dataFile = null;
try {
dataFile = new FileReader(userHomeLocal+"/Users/"+userEnteredString+".data");
} catch (FileNotFoundException ex) {
Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
}
String dbData = dataFile.toString();
try {
JSONObject dbObject = new JSONObject(dbData);
} catch (JSONException ex) {
Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(dbData);
JSONObject dataInfo = new JSONObject(dbData);
String password = dataInfo.getString("password");
System.out.println(password);
BufferedReader buffered = new BufferedReader(dataFile);
String test = null;
try {
test = buffered.readLine();
} catch (IOException ex) {
Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
}
The problem is when I print password it doesnt print anything, leading me to think that the password field is not processed.
here is an example of the database:
{"username":"user","password":"test"}
Thanks!
I don't believe FileReader.toString() is doing what you think it's doing. FileReader inherits toString from object, which means that it is just going to print out the reference, not the contents of the file, and yet you are trying to parse that as JSON. In that case you should have a severe log message though.
In order to read the contents of the file, you should use the read method on the reader or make it easy on yourself and use commons-io FileUtils#readFileToString or something similar.
I'm trying to find a way to save a video file. Initially I'd put the video files as blob data into a database, and now, I'm trying to get the blob data back, convert it into bytes, and then write it to a new file. I've been successful in doing this, but the problem is, I can't make the resulting files to run. I tried storing, retrieving, and writing .flv and .mp4 files, but neither work :/ Can anyone help me? Much appreciated! :)
Here is my code: :)
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(connectionURL, "root","password");
Statement st1 = (Statement) con.createStatement();
PreparedStatement pstmt = null;
ResultSet rs = null;
pstmt = con.prepareStatement("SELECT video_file from video where video_id = " + video_id);
rs = pstmt.executeQuery();
Blob blob = null;
byte[] blyte = null;
if(rs.next()) {
blob = rs.getBlob("video_file");
InputStream is = blob.getBinaryStream();
FileOutputStream fos = new FileOutputStream("C:\\Downloads\\file2.mp4");
int b = 0;
while(b != -1){
fos.write(b);
b = bis.read();
}
}
//exceptions beyond this point
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (ClassNotFoundException e) {
} catch (SQLException e) {
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
There is a '\0' byte written to fos in first iteration of the while-loop which does not come from bis.read().
I am writting the code to upload file on oracle as BLOB but while saving that file its giving me the exception java.sql.SQLException: ORA-01460: unimplemented or unreasonable
following are the functions to convert my blob type to byteArray
private byte[] convertToByteArray(Blob fromBlob) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
return convertToByteArrayImpl(fromBlob, baos);
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException ex) {
}
}
}
}
private byte[] convertToByteArrayImpl(Blob fromBlob, ByteArrayOutputStream baos)
throws SQLException, IOException {
byte[] buf = new byte[4000];
InputStream is = fromBlob.getBinaryStream();
try {
for (;;) {
int dataSize = is.read(buf);
if (dataSize == -1)
break;
baos.write(buf, 0, dataSize);
}
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
}
}
}
return baos.toByteArray();
}
I think its because my byte length is above 4000 but, what is the solution to save more than 4000 bytes?
One of the quirks of working with BLOBs in earlier versions of Oracle was that we could not include the full BLOB in an insert statement. It had to be a two-stage process.
The 4000 byte limit is the key, because that figure is the upper bound of what Oracle considers to be a SQL datatype. So Oracle can handle LOBs of 4000 bytes or less without a snatch but hurls the ORA-01460 exception if we ask it to accept a larger LOB. The workaround was to insert the row with an empty_blob() placeholder, and then update the new row.
insert into t42 (id, blob_col) values (1, empty_blob());
update t42
set blob_col = some_blob_variable
where id = 1;
This might be the cause of your problem; it is difficult to tell without seeing the whole of your code.
NB: As far as I can tell the preceding does not apply to Oracle 11g: we can now easily insert rows containing oversize BLOBs.