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();
Related
I'm trying to add blob data in a zip file. But files are getting corrupted while adding to a zip file. Below code executes, but not zipping the files:
public class BlobDataExtract {
static ZipOutputStream zos = null;
private static ZipOutputStream zosFile;
private static ZipOutputStream zipExtract() throws ClassNotFoundException, SQLException, IOException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(url, "user", "password");
String sql = "SELECT ORIG_NM,DOC_EXT_NM,DOC_INDX_NB,DOC_BO FROM zgdt099_document";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
java.sql.Blob docBlob = null;
DocumentTO dto = null;
List<DocumentTO> test = new ArrayList<DocumentTO>();
while (rs.next()) {
dto = new DocumentTO();
dto.setDocIndxNb(new Long(rs.getLong(AmpoDBConstants.DOC_INDX_NB)));
dto.setOrigNm(rs.getString(AmpoDBConstants.D_ORIG_NM));
dto.setDocExtNm(rs.getString(AmpoDBConstants.D_DOC_EXT_NM));
docBlob = rs.getBlob(AmpoDBConstants.D_DOC_BO);
// String filepathzipped =rs.getString(AmpoDBConstants.D_ORIG_NM) + ".zip";
InputStream blobStream = docBlob.getBinaryStream();
byte[] newFile = new byte[(int) docBlob.length()];
blobStream.read(newFile);
blobStream.close();
String contentType = "";
String extName = dto.getDocExtNm();
if ("pdf".equalsIgnoreCase(extName))
contentType = "application/pdf";
else if ("html".equalsIgnoreCase(extName) || "htm".equalsIgnoreCase(extName)
|| "stm".equalsIgnoreCase(extName) || "jpeg".equalsIgnoreCase(extName)
|| "jpg".equalsIgnoreCase(extName) || "bmp".equalsIgnoreCase(extName)
|| "gif".equalsIgnoreCase(extName))
contentType = "text/html";
else if ("xls".equalsIgnoreCase(extName) || "xla".equalsIgnoreCase(extName)
|| "xlc".equalsIgnoreCase(extName) || "xlm".equalsIgnoreCase(extName)
|| "xlw".equalsIgnoreCase(extName) || "csv".equalsIgnoreCase(extName)
|| "xlt".equalsIgnoreCase(extName))
contentType = "application/vnd.ms-excel";
else if ("doc".equalsIgnoreCase(extName) || "rtf".equalsIgnoreCase(extName)
|| "rtx".equalsIgnoreCase(extName))
contentType = "application/msword";
else if ("ppt".equalsIgnoreCase(extName) || "pps".equalsIgnoreCase(extName))
contentType = "application/vnd.ms-powerpoint";
else if ("mpp".equalsIgnoreCase(extName))
contentType = "application/vnd.ms-project";
else if ("txt".equalsIgnoreCase(extName))
contentType = "text/plain";
else if ("zip".equalsIgnoreCase(extName))
contentType = "application/zip";
else if ("ics".equalsIgnoreCase(extName))
contentType = "text/calendar";
else if ("snp".equalsIgnoreCase(extName))
contentType = "application/octet-stream";
else
contentType = "text/html";
FileContent fileCont = new FileContent(dto.getOrigNm(), newFile, contentType);
System.out.println("fileCont-->" + fileCont);
dto.setDocBO(fileCont);
test.add(dto);
try {
File file = new File(filePath);
FileOutputStream fos = new FileOutputStream("C:/Users/user/Desktop/test.zip");
zos = new ZipOutputStream(fos);
zos.putNextEntry(new ZipEntry(dto.getDocBO().getFullName()));
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
zos.write(bytes, 0, bytes.length);
} catch (FileNotFoundException ex) {
System.err.println("A file does not exist: " + ex);
} catch (IOException ex) {
System.err.println("I/O error: " + ex);
}
zos.closeEntry();
zos.close();
}
return zos;
}
}
Please help in modifying this code
Your code seems overly complex. It can be reduced to:
public class BlobDataExtract {
private static void zipExtract() throws SQLException, IOException {
String sql = "SELECT ORIG_NM,DOC_EXT_NM,DOC_INDX_NB,DOC_BO FROM zgdt099_document";
try (
Connection conn = DriverManager.getConnection("url", "user", "password");
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("C:/Users/user/Desktop/test.zip"));
) {
while (rs.next()) {
zos.putNextEntry(new ZipEntry(rs.getString(AmpoDBConstants.D_ORIG_NM)));
zos.write(rs.getBytes(AmpoDBConstants.D_DOC_BO));
}
}
}
}
Issue is resolved with the below code,
public class BlobDataExtract {
static ZipOutputStream zos =null;
static String url = "jdbc:oracle:thin:#hostname:1521:SID";
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(url, "user", "password");
String sql="select Blob_Data,ORIG_NM from table";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
byte[] docBlob = null;
String filename = null;
FileOutputStream fos = new FileOutputStream("C:/Users/test.zip");
zos = new ZipOutputStream(fos);
while (rs.next()) {
docBlob = rs.getBytes("Blob_Data");
filename = rs.getString("ORIG_NM");
try {
zos.putNextEntry(new ZipEntry(filename));
zos.write(docBlob, 0, Blob_Data.length);
}
catch (FileNotFoundException ex) {
System.err.println("A file does not exist: " + ex);
} catch (IOException ex) {
System.err.println("I/O error: " + ex);
}
zos.closeEntry();
}
}
}
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();
}
}
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);
}
}
}