Changed image color after fetch from database - java

I have problem with fetching image from database in Java. I wrote this function:
public byte[] fetchPhoto(Long id) throws SQLException {
Connection conn = DataSourceUtils.getConnection(dataSource);
byte[] photo = null;
Blob imageBlob = null;
try (ResultSet rs = conn.createStatement()
.executeQuery("select IMAGE from IMAGE_TABLE where IMAGE_ID = " + id)) {
while (rs.next()) {
imageBlob = rs.getBlob(1);
photo = imageBlob.getBytes(1, (int) imageBlob.length());
}
} catch (SQLException e) {
throw e;
} finally {
DataSourceUtils.releaseConnection(conn, dataSource);
}
return photo;
}
Ok, I have fetched image, but effect is like :
this
Orginal image
here
I don't know why after fetch I have this color. I checked this image in database so here is ok.

Maybe you need solution like here. So using this example, here is your improved method:
public byte[] fetchPhoto(Long id) throws SQLException {
Connection conn = DataSourceUtils.getConnection(dataSource);
byte[] photo = null;
Blob imageBlob = null;
try (ResultSet rs = conn.createStatement()
.executeQuery("select IMAGE from IMAGE_TABLE where IMAGE_ID = " + id)) {
while (rs.next()) {
imageBlob = rs.getBlob(1);
photo = imageBlob.getBytes(1, (int) imageBlob.length());
ByteArrayInputStream bais = new ByteArrayInputStream(photo);
BufferedImage bf = ImageIO.read(bais);
BufferedImage nbf = new BufferedImage(bf.getWidth(),
bf.getHeight(), BufferedImage.TYPE_INT_RGB);
nbf.createGraphics().drawImage(bf, 0, 0, Color.WHITE, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(nbf, "jpg", baos);
photo = baos.toByteArray();
}
} catch (SQLException e) {
throw e;
} finally {
DataSourceUtils.releaseConnection(conn, dataSource);
}
return photo;
}
If I were you I moved this code to separete method.

Related

Result set closed exception when trying to read a pdf file from sqlite table

I am trying to read a pdf file that has been stored in a table on SQLite database. when I run the Code it says ' Resultset is closed'.
public void syllabusAttach(){
String selectSQL = "SELECT Image_Reg FROM "+getRegulation()+" WHERE SubjectCode="+getSubCode()+"";
ResultSet rs = null;
FileOutputStream fos = null;
Connection conn = null;
Statement stmt = null;
try {
conn = connect();
stmt = conn.createStatement();
rs = stmt.executeQuery(selectSQL);
// write binary stream into file
InputStream is =rs.getBinaryStream("Image_Reg");
File file = new File("syllabus_"+getRegulation()+".pdf");
OutputStream os = new FileOutputStream(file);
System.out.println("Writing BLOB to file " + file.getAbsolutePath());
byte[] content = new byte[1024];
int size = 0;
while((size = is.read(content)) !=-1){
os.write(content,0,size);
}
} catch (SQLException | IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
if (fos != null) {
fos.close();
}
} catch (SQLException | IOException e) {
System.out.println(e.getMessage());
}
}
}
write binary stream into file
File file = new File("syllabus_"+getRegulation()+".pdf");
fos = new FileOutputStream(file);
System.out.println("Writing BLOB to file " + file.getAbsolutePath());
while (rs.next()) {
InputStream input = rs.getBinaryStream("Image_Reg");
byte[] buffer = new byte[1024];
while (input.read(buffer) > 0) {
fos.write(buffer);
}
}
When I did the above changes to the code, I could see that the files are being generated but when I open them it says "this file cannot be opened"
I found that the getSubCode() in the SQl query is not returning a the desired string which is leading to the error.

How to get byte Image From url in Android

I am new to android.The Image is store in server by Base64 format. so how can i get it from server to My Project and set to my ImageView using Json Object.
Please Help me
Any help will be Appappreciated
Try this:
Convert Url to byte[] first:
byte[] bitmapdata = getByteArrayImage(url);
Method:
private byte[] getByteArrayImage(String url){
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
Now convert the byte[] to bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata , 0, bitmapdata .length);
And set your bitmap to your ImageView:
img= (ImageView) findViewById(R.id.imgView);
img.setImageBitmap(bitmap );
I found easy solution:
byte[] img = Base64.decode(userHeader.GetImage(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
imageww.setImageBitmap(getCircleBitmap(bitmap));
Using Apache's commons-io-2.5 lib we can get using this function IOUtils.toByteArray(is)
public static String getByteArrayFromURL(final String url) {
String base64Image = "";
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> result = executor.submit(new Callable<String>() {
public String call() throws Exception {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
return Base64.encodeToString(IOUtils.toByteArray(is), Base64.NO_WRAP);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
});
try {
base64Image = result.get();
} catch (Exception exception) {
exception.printStackTrace();
}
return base64Image;
}

How to upload file in database?

I am trying to upload an image file with the code below, but the file is not being uploaded. The console still shows the message "1 Record Successfully Inserted."
Create table image
(
name varchar2(20),
photo blob
);
import java.sql.*;
import java.io.*;
public class ImageWriter {
static Connection connection = null;
static CallableStatement pstat = null;
static String connectionURL = null;
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "SYSTEM", "SYSTEM");
PreparedStatement pstat = connection.prepareStatement("insert into image(name,photo) values(?,?)");
FileInputStream fin = new FileInputStream("E:\\test.jpg");
pstat.setString(1, "ABC");
pstat.setBinaryStream(2, fin,fin.available());
int result = pstat.executeUpdate();
System.out.println(result + " Record Successfully Inserted");
connection.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
The above code works fine.
I dont know how you verified the contents of database.
Here is my code to verify the db(blob column): Try with this method. I used your code to insert the image and I could retrieve the image successfully. (note : file extension should be same)
public static void getPic() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl", "sys as sysdba",
"Oracle123");
ResultSet rs = null;
Statement stmt = null;
oracle.sql.BLOB photo = null;
conn.setAutoCommit(false);
stmt = conn.createStatement();
String name="ABC";
rs = stmt.executeQuery("select photo from image where name = '" + name + "'" );
rs.next();
photo = ((OracleResultSet) rs).getBLOB(1);
File f = new File("E:/image2.jpg");
f.getParentFile().mkdirs();
f.createNewFile();
InputStream in = photo.getBinaryStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream outputStream = new FileOutputStream(f);
int bufferSize = 1024;
int length = (int) photo.length();
byte[] buffer = new byte[bufferSize];
while((length = in.read(buffer)) != -1) {
out.write(buffer,0,length);
}
out.writeTo(outputStream);
System.out.println("Image Retrieved");
out.close();
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

Buffered image as JPG over Tomcat Websocket to HTML 5 Canvas

Hey we want to send buffered images periodically over tomcat websockets into a canvas, kind of a livestream.
Server Code:
private static void broadcastImage(BufferedImage img) {
StreamInbound someClient;
byte[] arr = BufferedImageToByte(img);
ListIterator<StreamInbound> iter = clients.listIterator();
while (iter.hasNext()) {
someClient = (MessageInbound) iter.next();
try {
someClient.getWsOutbound().writeBinaryMessage(ByteBuffer.wrap(arr));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static byte[] BufferedImageToByte(BufferedImage img) {
byte[] imageInBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
imageInBytes = baos.toByteArray();
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
return imageInBytes;
}
the problem is how to pack this into the canvas.
Client Code:
ws = new WebSocket("ws://"+ location.host + "/carduinowebdroid/websocket");
ws.binaryType = "arraybuffer";
/** stuff **/
ws.onmessage = function(message){
if (message.data instanceof ArrayBuffer) {
streamHandleMessage(message);
}
}
function streamHandleMessage(message) {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
/** what now? **/
}
Any help is greatly appreciated!
Do you really need a webSocket?
If not:
var can = document.getElementById('canvas');
var ctx = can.getContext('2d');
var img = new Image();
img.onload = function(){
can.width = img.width;
can.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
}
img.src = 'img.jpg';
Otherwise have a look at this:
How can I create a canvas imageData array from an arrayBuffer representation of a JPG
or this
http://www.adobe.com/devnet/html5/articles/real-time-data-exchange-in-html5-with-websockets.html

java insert Blob as ByteArrayOutputStream get ClassCastException

I've to save a pdf file represented as a ByteArrayOutputStream into a Blob SQL field of a table, here's my code:
public boolean savePDF(int version, ByteArrayOutputStream baos) throws Exception{
boolean completed = false;
ConnectionManager conn = new ConnectionManager();
try {
PreparedStatement statement = conn.getConnection().prepareStatement(INSERT_PDF);
statement.setLong(1, version);
statement.setBlob(2, (Blob)baos);
statement.execute();
conn.commit();
completed = true;
} catch (SQLException e) {
conn.rollbackQuietly();
e.printStackTrace();
throw e;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
conn.close();
}
return completed;
}
But I get a java.lang.ClassCastException:
java.io.ByteArrayOutputStream cannot be cast to java.sql.Blob
How can I manage that? Thanks
There is a setBlob that takes an InputStream, so
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
statement.setBlob(2, bais);
You can't cast ByteArrayOutputStream to Blob. Try creating the Blob instance as below:
SerialBlob blob = new SerialBlob(baos.toByteArray());
and then
statement.setBlob(2, blob);

Categories

Resources