Trying to insert image/xml file as blob in cassandra database - java

Actually I need to insert xml file in cassandra database. So initially am trying to insert image as a blob content later I change the code to insert xml but am facing issues in insert and retrieve the blob content as image. Can anyone suggest which is the best practice to insert image/xml file in cassandra database.
FileInputStream fis=new FileInputStream("C:/Users/anand.png");
byte[] b= new byte[fis.available()+1];
int length=b.length;
fis.read(b);
System.out.println(length);
ByteBuffer buffer =ByteBuffer.wrap(b);
PreparedStatement ps = session.prepare("insert into usersimage (firstname,lastname,age,email,city,length,image) values(?,?,?,?,?,?,?)");
BoundStatement boundStatement = new BoundStatement(ps);
int age=22;
//System.out.println(buffer);
session.execute( boundStatement.bind( "xxx","D",age,"xxx#gmail.com","xxx",length,buffer));
//session.execute( boundStatement.bind( buffer, "Andy", length));
PreparedStatement ps1 = session.prepare("select * from usersimage where email =?");
BoundStatement boundStatement1 = new BoundStatement(ps1);
ResultSet rs =session.execute(boundStatement1.bind("ramya1#gmail.com"));
ByteBuffer bImage=null;
for (Row row : rs) {
bImage = row.getBytes("image") ;
length=row.getInt("length");
}
byte image[]= new byte[length];
image=Bytes.getArray(bImage);
HttpServletResponse response = null;
#SuppressWarnings("null")
OutputStream out = response.getOutputStream();
response.setContentType("image/png");
response.setContentLength(image.length);
out.write(image);
Am facing issues while retrieving the blob content as image. could anyone please help me on this.

You are inserting data to an email and selecting from another;
A better way to read the bytes of an image would be:
BufferedImage originalImage = ImageIO.read(new File("C:/Users/anand.png"));
ByteArrayOutputStream imageStream = new ByteArrayOutputStream();
ImageIO.write(originalImage, "png", imageStream );
imageStream.flush();
byte[] imageInByte = imageStream.toByteArray();

Related

Image to ByteArray to BLOB and BLOB to ByteArray to Image Conversion Issues in Java

After a lot of learning on ByteArrays & BLOBS, I managed to write the below Java code to write an image into Access DB (Using ucanaccess) and writing it back to Disk.
When I write an image back to disk the image is in incorrect format or something is messed up that you cannot open that image.
I understand it is not a good practice to store Images on DB but, this is only for my learning.
public static void Update_to_DB() throws SQLException, IOException {
String URL = "jdbc:ucanaccess://C:\\Users\\bharat.nanwani\\Desktop\\Images.accdb";
Connection conn = DriverManager.getConnection(URL);
//Statement stmt = conn.createStatement();
PreparedStatement p;
File ImgPath = new File("C:\\Users\\bharat.nanwani\\Desktop\\Desert.jpg");
BufferedImage bufferedimage = ImageIO.read(ImgPath);
WritableRaster raster = bufferedimage.getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
byte[] bytearray = date.getdata();
String query = "INSERT INTO Images(data) VALUES(?);";
p = conn.prepareStatement(query);
p.setBinaryStream(1, new ByteArrayInputStream(bytearray),bytearray.length);
p.execute();
}
public static void update_to_DISK() throws SQLException, IOException {
String URL = "jdbc:ucanaccess://C:\\Users\\bharat.nanwani\\Desktop\\Images.accdb";
Connection conn = DriverManager.getConnection(URL);
PreparedStatement p;
ResultSet rs;
String query = "SELECT Data FROM Images";
p=conn.prepareStatement(query);
rs = p.executeQuery();
if (rs.next()) {
Blob blob = rs.getBlob("Data");
byte[] bytearray = blob.getBytes(1L, (int)blob.length());
FileOutputStream fos = new FileOutputStream("C:\\Users\\bharat.nanwani\\Desktop\\New Folder\\test.jpg");
fos.write(bytearray);
fos.close();
System.out.println(bytearray);
}
}
Firstly, you should separate this into two parts:
Storing binary data in a database and retrieving it
Loading an image file and saving it again
There's no need to use a database to test the second part - you should diagnose the issues by loading the image and saving straight to a file, skipping the database.
No, I believe the problem is that you're copying the data from the WritableRaster's databuffer, and then saving that to a .jpg file. It's not a jpeg at that point - it's whatever the internal format of the WritableRaster uses.
If you want a jpeg file, you don't need to use ImageIO at all - because you've started off with a jpeg file. If you want to start and end with the same image, just copy the file (or save the file to the database, in your case). That's just treating the file as bytes.
If you need to do something like saving in a different format, or at a different size, etc, then you should ask the ImageIO libraries to save the image as a JPEG again, re-encoding it... and then store the result as a file or in the database etc.
read the image file using FileInputStream rather than WritableRaster
and then store Image file in database using setBinaryStream() method of PreparedStatement..
it will store the file in bytes.
also while getting file back from database use getBytes() method of ResultSet and store it using FileOutputStream
public static void Update_to_DB() throws SQLException, IOException {
String URL = "jdbc:ucanaccess://C:\\Users\\bharat.nanwani\\Desktop\\Images.accdb";
Connection conn = DriverManager.getConnection(URL);
//Statement stmt = conn.createStatement();
PreparedStatement p;
File ImgPath = new File("C:\\Users\\bharat.nanwani\\Desktop\\Desert.jpg");
FileInputStream fin = new FileInputStream(ImgPath);
String query = "INSERT INTO Images(Data) VALUES(?);";
p = conn.prepareStatement(query);
p.setBinaryStream(1, fin);
p.execute();
}
public static void update_to_DISK() throws SQLException, IOException {
String URL = "jdbc:ucanaccess://C:\\Users\\bharat.nanwani\\Desktop\\Images.accdb";
Connection conn = DriverManager.getConnection(URL);
PreparedStatement p;
ResultSet rs;
String query = "SELECT Data FROM Images";
p = conn.prepareStatement(query);
rs = p.executeQuery();
if (rs.next()) {
byte[] bytearray = rs.getBytes("Data");
FileOutputStream fos = new FileOutputStream("C:\\Users\\bharat.nanwani\\Desktop\\New Folder\\test.jpg");
fos.write(bytearray);
fos.close();
System.out.println(bytearray);
}
}
it will solve your problem..
Below is what I'm doing to write to DB -
public static void main(String[] Args) throws SQLException, IOException {
String URL = "jdbc:ucanaccess://C:\\Users\\bharat.nanwani\\Desktop\\Images.accdb";
Connection conn = DriverManager.getConnection(URL);
PreparedStatement p;
File ImgPath = new File("C:\\Users\\bharat.nanwani\\Desktop\\Desert.jpg");
FileInputStream fileinput = new FileInputStream(ImgPath);
byte[] bytearray = new byte[(int)ImgPath.length()];
String query = "INSERT INTO Images(data) VALUES(?);";
p = conn.prepareStatement(query);
//p.setBinaryStream(1, new ByteArrayInputStream(bytearray),bytearray.length);
p.setBytes(1, bytearray);
p.execute();
}

How to add a photo to mysql from java?

I've created a software using netbeans. now I want to add pictures to my database. I have created a table and changed the type as 'BLOB'. But, IDK how to code in java to do this.
with this, I get a image and set it to a jLabel.
now how to save this photo in mysql?
try {
lbl_imge1.setIcon(null);
jFileChooser1.showOpenDialog(this);
BufferedImage upload = ImageIO.read(jFileChooser1.getSelectedFile());
java.awt.Image photo = upload.getScaledInstance(lbl_imge1.getWidth(), lbl_imge1.getHeight(), java.awt.Image.SCALE_SMOOTH);
lbl_imge1.setIcon(new ImageIcon(photo));
} catch (Exception e) {
e.printStackTrace();
}
Now I am here,
try {
jLabel1.setIcon(null);
jFileChooser1.showOpenDialog(this);
BufferedImage upload = ImageIO.read(jFileChooser1.getSelectedFile());
java.awt.Image photo = upload.getScaledInstance(jLabel1.getWidth(), jLabel1.getHeight(), java.awt.Image.SCALE_SMOOTH);
jLabel1.setIcon(new ImageIcon(photo));
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/crazy", "root", "123");
BufferedImage buffered = ImageIO.read(jFileChooser1.getSelectedFile());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(buffered, "jpg", baos);
byte[] imageInByte = baos.toByteArray();
Blob blob = con.createBlob();
blob.setBytes(1, imageInByte);
String query="INSERT INTO image VALUES ('"+jTextField1.getText()+"','"+blob+"')";
PreparedStatement statement=con.prepareStatement(query);
Take your BufferedImage
BufferedImage buffered= ImageIO.read(jFileChooser1.getSelectedFile());
Get a byte array from it (From this answer)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(buffered, "jpg", baos );
byte[] imageInByte = baos.toByteArray();
Save byte array as blob (From this answer) (probably use a Prepared Statement)
Blob blob = connection.createBlob();
blob.setBytes(1, imageInByte);
UPDATE: connection is your database connector i.e:
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
You can save any byte array to a blob column. I know that this is possible with Oracle and this also should work with MySql. Here is a small example how to do a insert with java code:
String sql = "insert into yourtable(id,binaryImage) values (?,?)";
PreparedStatement pstmt =dbConnection.prepareStatement(sql);
ByteArrayInputStream bais = new ByteArrayInputStream(your_byte_array);
pstmt.setString(1, "your_id");
pstmt.setBinaryStream(2, bais);
pstmt.execute();
pstmt.close();

inserting image to sqlite

I'm creating application using sqlite database and netbeans .I have a problem when I save an image to data base.
I have an image field in database which data type is BLOB and i'm inserting a byte array . i know it doesn't match.but when i save it holds value like this "[B#2c8f544b" but actual values should be like this "BLOB (Size: 1850)". if there is some value like that then only i can retrieve the image. I really can't figure out how to do this.if you have any reference please let me know.
my idea is before save to database convert byte array to BLOB type.but I couldn't find any code.
String fname = p.fname;
String lname = p.lname;
byte[] image = p.image_det;
String mob = p.mobile;
String wor = p.work;
String hom = p.home;
String fax = p.fax;
int pID ;
ResultSet rst = stmt.executeQuery("SELECT MAX(pID) FROM person");
pID = Integer.parseInt(rst.getString(1))+1;
Statement stmt1 = con.createStatement();
stmt1.executeUpdate("INSERT INTO person(pID,F_name,L_name,image) VALUES ("+pID+" ,'"+fname+"','"+lname+"','"+image+"' ) ");
//-------------------------getting image path and get image data to array called image_details
File f;
String ipath = f.getAbsolutePath(); // getting image path
byte[] image_detail = null;
try
{
File image = new File(ipath);
FileInputStream fis = new FileInputStream(image);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for(int readNum;(readNum = fis.read(buf))!= -1;)
{
baos.write(buf, 0,readNum);
}
image_detail = baos.toByteArray();
per.setImage_det(image_detail); // set image data for person class

How to save and load an image to a mysql database in Java?

How do you save and load an image from a database and display it in Java? I can get the file location, but I am unsure as to how to save it as a blob in the database or display the image in a swing window. I am using a PreparedStatement to get information in and out of the database.
See this MySQL Java tutorial for examples under the sections Writing images and Reading images. In outline,
// writing
String sql = "INSERT INTO Images(Data) VALUES(?)";
PreparedStatement pst = con.prepareStatement(sql);
FileInputStream fin = new FileInputStream(myFile);
pst.setBinaryStream(1, fin, (int) myFile.length());
pst.executeUpdate();
//reading
String query = "SELECT Data FROM Images LIMIT 1";
PreparedStatement pst = con.prepareStatement(query);
ResultSet result = pst.executeQuery();
result.next();
String fileName = "src/main/resources/tree.png";
FileOutputStream fos = new FileOutputStream(fileName);
Blob blob = result.getBlob("Data");
int len = (int) blob.length();
byte[] buf = blob.getBytes(1, len);
fos.write(buf, 0, len);

Snippet to create a file from the contents of a blob in Java

I have some files stored in a database blob column in Oracle 9.
I would like to have those files stored in the file system.
This should be pretty easy, but I don't find the right snipped.
How can I do this in java?
PreparedStatement ptmst = ...
ResutlSet rs = pstmt.executeQuery();
rs.getBlob();
// mistery
FileOutputStream out = new FileOutputStream();
out.write(); // etc et c
I know it should be something like that... what I don't know is what is commented as mistery
Thanks
EDIT
I finally got this derived from David's question.
This is my lazy implementation:
PreparedStatement pstmt = connection.prepareStatement("select BINARY from MYTABLE");
ResultSet rs = pstmt.executeQuery();
while( rs.next() ) {
Blob blob = rs.getBlob("BINARY");
System.out.println("Read "+ blob.length() + " bytes ");
byte [] array = blob.getBytes( 1, ( int ) blob.length() );
File file = File.createTempFile("something-", ".binary", new File("."));
FileOutputStream out = new FileOutputStream( file );
out.write( array );
out.close();
}
You'd want to get the blob as an inputstream and dump its contents to the outputstream. So 'misery' should be something like:
Blob blob = rs.getBlob(column);
InputStream in = blob.getBinaryStream();
OutputStream out = new FileOutputStream(someFile);
byte[] buff = new byte[4096]; // how much of the blob to read/write at a time
int len = 0;
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
If you find yourself doing a lot of IO work like this, you might look into using Apache Commons IO to take care of the details. Then everything after setting up the streams would just be:
IOUtils.copy(in, out);
There is another way of doing the same operation faster. Actually the answer above works fine but like IOUtils.copy(in,out) it takes a lot of time for big documents. The reason is you are trying to write your blob by 4KB iteration. Simplier solution :
Blob blob = rs.getBlob(column);
InputStream in = blob.getBinaryStream();
OutputStream out = new FileOutputStream(someFile);
byte[] buff = blob.getBytes(1,(int)blob.getLength());
out.write(buff);
out.close();
Your outputStream will write the blob in one shot.
Edit
Sorry didn't see the Edit section on the intial Post.

Categories

Resources