I'm trying to create a PDF based on the information that resides on a database. Know I need to retrieve a TIFF image that is stored as a BLOB on a mysql database from Java. And I don't know how to do it. The examples I've found shows how to retrieve it and save it as a File (but on disk) and I needed to reside on memory.
Table name: IMAGENES_REGISTROS
BLOB Field name: IMAGEN
Any Ideas?
On your ResultSet call:
Blob imageBlob = resultSet.getBlob(yourBlobColumnIndex);
InputStream binaryStream = imageBlob.getBinaryStream(0, imageBlob.length());
Alternatively, you can call:
byte[] imageBytes = imageBlob.getBytes(1, (int) imageBlob.length());
As BalusC noted in his comment, you'd better use:
InputStream binaryStream = resultSet.getBinaryStream(yourBlobColumnIndex);
And then the code depends on how you are going to read and embed the image.
imagebytes = rs.getBytes("images");
image=getToolkit().createImage(imageBytes);
Image img = image.getScaledInstance(100,100,Image.SCALE_SMOOTH);
ImageIcon icon=new ImageIcon(img);
jLabel6.setIcon(icon);
Try this code to get adjustable image from blog Mysql in netbeans
final String dbURL = "jdbc:mysql://localhost:3306/portfolio";
final String dbUser = "root";
final String dbPass = "";
Connection conn = null;
Statement stmt = null;
try {
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
System.out.println("db connected");
stmt = (Statement) conn.createStatement();
ResultSet rs1;
rs1 = stmt.executeQuery("select profileImage from tbl_welcome where id = 1117");
if (rs1.next()) {
byte[] imgData = rs1.getBytes("profileImage");//Here....... r1.getBytes() extract byte data from resultSet
System.out.println(imgData);
response.setHeader("expires", "0");
response.setContentType("image/jpg");
OutputStream os = response.getOutputStream(); // output with the help of outputStream
os.write(imgData);
os.flush();
os.close();
}
} catch (SQLException ex) {
// String message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
private void loadFileDataBlobFromDataBase()
{
List<Blob> bFile = jdbcTemplate.query(sql, new RowMapper<Blob>() {
#Override
public Blob mapRow(ResultSet rs, int rowNum)
throws SQLException {
return rs.getBlob(1);
}
});
if (bFile != null && bFile.size() > 0) {
bufReader = new BufferedReader(new InputStreamReader(bFile.get(
0).getBinaryStream()));
}
if (null != bufReader) {
dataVO record = null;
String lineStr = bufReader.readLine();
record = (dataVO) lineMapper.mapLine(lineStr, 1);
}
}
}
Related
I have poor knowledge about programming. I need to save image in MySQL database. I have created a database table and there is a column to add image with longblob data type.
I have code to a button to choose image from folder in PC then it load to a jlable. Now I need to insert this image to a database.
This is my code;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc=new JFileChooser();
fc.showOpenDialog(this);
File f=fc.getSelectedFile();
String path=f.getAbsolutePath();
jLabel1.setIcon(new ImageIcon(path));
try{
FileInputStream fin=new FileInputStream(f);
int len=(int)f.length(); Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/hss", "root", "bis123");
PreparedStatement ps=con.prepareStatement("Insert into profile values(?)");
ps.setBinaryStream(1, fin, len);
int status=ps.executeUpdate();
if(status > 0) {
jLabel2.setText("Successfully inserted in DB");
}else{
jLabel2.setText("Image not inserted!");
}
}catch(Exception e){
System.out.println(e);
}
}
In MySQL when we use the blob type to store the data , it support only 5 kb image capacity.
CREATE TABLE image (
id varchar(45) DEFAULT NULL,
size int(11) DEFAULT NULL,
image longblob
);
created database table in above code
this is java code to insert image in database
import java.sql.*;
import java.io.*;
public class InsertImagesMysql{
public static void main(String[] args){
System.out.println("Insert Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String userName = "root";
String password = "root";
Connection con = null;
try{
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
File imgfile = new File("pic.jpg");
FileInputStream fin = new FileInputStream(imgfile);
PreparedStatement pre =
con.prepareStatement("insert into Image values(?,?,?)");
pre.setString(1,"test");
pre.setInt(2,3);
pre.setBinaryStream(3,(InputStream)fin,(int)imgfile.length());
pre.executeUpdate();
System.out.println("Successfully inserted the file into the database!");
pre.close();
con.close();
}catch (Exception e1){
System.out.println(e1.getMessage());
}
}
}
here is code to retrieve data from database
import java.io.*;
import java.sql.*;
public class RetriveImagesMysql{
public static void main(String[] args){
System.out.println("Retrive Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String userName = "root";
String password = "root";
Connection con = null;
try{
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select image from image");
int i = 0;
while (rs.next()) {
InputStream in = rs.getBinaryStream(1);
OutputStream f = new FileOutputStream(new File("test"+i+".jpg"));
i++;
int c = 0;
while ((c = in.read()) > -1) {
f.write(c);
}
f.close();
in.close();
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}
here just assign fin to jbutton action event it will trigger automatically the run of the code
This is my Java code in eclipse:
#GET
#Path("request=getTile")
#Produces({"image/png"})
public BufferedImage getTileGET(#QueryParam("id_photo")String id_photo,
#QueryParam("x")String x,
#QueryParam("y")String y,
#QueryParam("zoom")String zoom) throws SQLException, IOException {
BufferedImage BI = null;
connection dbs = new connection();
Statement statement = null;
Connection con = dbs.getConnection();
PreparedStatement ps = null;
try {
ps = con.prepareStatement("SELECT image from tiles where id_photo = '"+id_photo+"' "
+ "and x ='"+x+"' and y ='"+y+"' and zoom = '"+zoom+"';");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
InputStream input = rs.getBinaryStream("image");
BI=ImageIO.read(input);
input.close();
}
}
catch (SQLException e )
{
e.printStackTrace();
System.out.println("Bad data");
}
finally {
if (statement != null) {
statement.close();
}
if (con != null) {
con.close();
}
}
return BI;
}
My problem is that the image is not displayed in the Browser ( Google Chrome ).
My image in database is in bytea. What am I doing wrong? Thank you for any help.
You cannot simply return an image like that. See this example: https://stackoverflow.com/a/9204824/1256583
#GET
#Path("request=getTile")
#Produces({"image/png"})
public Response getTileGET(...) {
BufferedImage image = ...;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
byte[] imageData = baos.toByteArray();
// uncomment line below to send non-streamed
// return Response.ok(imageData).build();
// uncomment line below to send streamed
// return Response.ok(new ByteArrayInputStream(imageData)).build();
I need to read a file by column and I need to store it in a database. My problem is the file contents are not stored in the database and the code just read the contents. I am getting an error in storing it.
Code:
public class Test3 {
private static String vrms;
private static String irms;
private static String total;
public static Connection getConnection() {
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test3";
String username = "root";
String password = "";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username,password);
System.out.println("Connection Established");
return conn;
} catch (Exception e) {
System.out.println("Connection not established");
return null;
} }
public static void main(String[] args) throws Exception {
FileInputStream fstream = new FileInputStream("D:/data/database.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
strLine.split(" ");
System.out.println(strLine);
}
in.close();
FileInputStream fis = null;
PreparedStatement pstmt = null;
Connection conn = null;
try {
conn = getConnection();
conn.setAutoCommit(false);
File file = new File(strLine);
fis = new FileInputStream(file);
pstmt = conn.prepareStatement("insert into meter1(vrms, irms, total) values (?, ?, ?)");
pstmt.setString(1, vrms);
pstmt.setString(2, irms);
pstmt.setString(3, total);
pstmt.executeUpdate();
conn.commit();
}
catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
} finally {
pstmt.close();
fis.close();
conn.close();
}}}
error:
10 11 0
12 13 0
14 15 0
Connection Established
Error: null
java.lang.NullPointerException
at java.io.File.(Unknown Source)
at vidhya.Test3.main(Test3.java:71)
Exception in thread "main" java.lang.NullPointerException
at vidhya.Test3.main(Test3.java:85)
This is sample code which might be helpful..
Replace the column names with correct db columns.
public static void main(String[] args) throws IOException, SQLException {
PreparedStatement preparedstatement = null;
try{
String read=null;
in = new BufferedReader(new FileReader("patientlist.txt"));
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
name=splited[0];
age=splited[1];
height=splited[2];
weight=splited[3];
addpatient(connection, preparedstatement, name, age, height, weight);
}
}
catch (IOException e) {System.out.println("There was a problem: " + e);}
if (connection != null)
try{connection.close();} catch(SQLException ignore){}
}
public static void addpatient(Connection connection, PreparedStatement preparedstatement, String name, String age, String height, String weight) throws SQLException{
preparedstatement=connection.prepareStatement("insert into allpatients(name, age, height, weight) values(?,?,?,?)");
preparedstatement.setString(1, name);
preparedstatement.setString(2, age);
preparedstatement.setString(3, height);
preparedstatement.setString(4, weight);
preparedstatement.executeUpdate();
}
You have not stored information read from the file in any variable (vrms, irms or total). Correct your code before posting here for the issue.
Posting the sample data file and column data types will be helpful.
I've tried the following code to retrieve an image stored in the oracle database with BLOB datatype. Upon running it in apace tomcat7 server i could only see an image icon(may be a broken image) but not an image. When I tried to open the image icon it got downloaded. I opened the downloaded image using picasa but it displayed "invalid image".
PLEASE try solving my problem....!!
public class RetrieveInkblot extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Blob photo = null;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String query = "select img from inkblots where bid = 23";
ServletOutputStream out = response.getOutputStream();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "system", "manager");
out.println("Connection");
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
if (rs == null) {
out.print("null except");
} else if (rs.next()) {
photo = rs.getBlob(1);
} else {
response.setContentType("text/html");
out.println("<html><head><title>Person Photo</title></head>");
out.println("<body><h1>No photo found for id= 001 </h1></body></html>");
return;
}
byte[] imgData = photo.getBytes(1, (int) photo.length());
response.setContentType("image/jpg");
OutputStream o = response.getOutputStream();
o.write(imgData);
o.flush();
o.close();
} catch (Exception e) {
response.setContentType("text/html");
out.println("<html><head><title>Error: Person Photo</title></head>");
out.println("<body><h1>Error=" + e.getMessage() + "</h1></body></html>");
return;
}
}
}
Your error is in this line:
byte[] imgData = photo.getBytes(1,(int)photo.length());
Note that java starts counting by 0, so change it to this line:
byte[] imgData = photo.getBytes(0,(int)photo.length());
If this gives you a IndexOutOfBoundsException, you also need to decrement photo.length():
byte[] imgData = photo.getBytes(0,(int)photo.length()-1);
By the way I wouldn't save the picture in the database, I would either write the image into your server and write the url into database, or encode the image with base64 witch is easier to read back.
I work on a java program that needs to insert/retrieve from/to DB (SQL server 2008 R2). Can any one help me?
public void insertImage(Connection conn,String img)
{
int len;
String query;
PreparedStatement pstmt;
try
{
File file = new File(img);
FileInputStream fis = new FileInputStream(file);
len = (int)file.length();
query = ("insert into TableImage VALUES(?,?,?)");
pstmt = conn.prepareStatement(query);
pstmt.setString(1,file.getName());
pstmt.setInt(2, len);
// Method used to insert a stream of bytes
pstmt.setBinaryStream(3, fis, len);
pstmt.executeUpdate();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void getImageData(Connection conn)
{
byte[] fileBytes;
String query;
try
{
query = "select data from tableimage";
Statement state = conn.createStatement();
ResultSet rs = state.executeQuery(query);
if (rs.next())
{
fileBytes = rs.getBytes(1);
OutputStream targetFile=
new FileOutputStream(
"d://filepath//new.JPG");
targetFile.write(fileBytes);
targetFile.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}