Saving an image in MySQL from Java - java

I am trying to save images in MySQL database from a Java swing application. I am using JFileChsoser to get the path of the image. Then after that converting the file so that it can be saved in the MySQL column which is of BLOB type. But every image I try to save does not save properly or get converted properly. Could someone tell me what I'm doing wrong over here?
private void btn_choosepicActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser picchooser = new JFileChooser();
picchooser.setDialogTitle("Select Image");
picchooser.showOpenDialog(null);
File pic=picchooser.getSelectedFile();
path= pic.getAbsolutePath();
txt_path.setText(path.replace('\\','/'));
try{
File image = new File(path);
FileInputStream fis = new FileInputStream(image);
ByteArrayOutputStream baos= new ByteArrayOutputStream();
byte[] buff = new byte[1024];
for(int readNum; (readNum=fis.read(buff)) !=-1 ; ){
baos.write(buff,0,readNum);
}
userimage=baos.toByteArray();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
And then after this Im saving it to the database like so.
private void btn_saveActionPerformed(java.awt.event.ActionEvent evt) {
String user= txt_username.getText();
try{
String sql="insert into imgtst (username,image) values ('"+user+"','"+userimage+"')";
pst=con.prepareStatement(sql);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Saved");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
and I have declared the variable userimage and path as a global variables
String path=null;
byte[] userimage=null;

You are converting the byte[] to a String in your sql statement, and you will end up with incorrect data.
The right way to use a BLOB would be to pass the InputStream itself. You can use the FileInputStream you are using to read the file.
File image = new File(path);
FileInputStream fis = new FileInputStream ( image );
String sql="insert into imgtst (username,image) values (?, ?)";
pst=con.prepareStatement(sql);
pst.setString(1, user);
pst.setBinaryStream (2, fis, (int) file.length() );
When you retrieve it back you can similarly get an InputStream from the ResultSet:
InputStream imgStream = resultSet.getBinaryStream(2);

Related

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

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();

Prevent downloaded files from replacing or overwriting each other

How to download all file types in MySQL database using Java app and prevent one file from replacing the other?
How can I include all file types in my filepath=("D:\\sch work\\skirt\\filename.pdf"); so that I am able to download pdf, docx, jpeg etc, from a MySQL database using Java mouse click event on a JTable?
I have two problems.
I can only open a PDF files although I want to open docs, JPEG and img files.
Every time I download another file from a different row it replaces the existing one. I would like to keep all of them
Below please find my code for mouse click event and please suggest what I should add for it to work as I need it.
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
String filePath =("D:\\sch work\\skirt\\filename.pdf");
int BUFFER_SIZE = 4096;
try {
int cert_code= jTable1.getSelectedRow();
String tableClick=(jTable1.getModel().getValueAt(cert_code,3).toString());
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee_certificate","root","");
String sql= "SELECT cert FROM certificate WHERE cert_code =?" ;
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, tableClick);
ResultSet rs=pstmt.executeQuery();
if(rs.next()){
Blob blob = rs.getBlob("cert");
InputStream inputStream = blob.getBinaryStream();
OutputStream outputStream = new FileOutputStream(filePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
//JOptionPane.showMessageDialog(null,"file saved")
} }
catch (Exception e)
{JOptionPane.showMessageDialog(null,e);}
}
If you want something other than PDF, you should store what's in that cert blob, so you can send out the appropriate filename/type:
You get PDF because that's the exact+only file type you write out to:
String filePath =("D:\\sch work\\skirt\\filename.pdf");
^^^
Perhaps something more like (in pseudo-code):
select cert,filename,filetype from ...
filepath = 'd:\sch work\skirt' + filename
header('Content-type: ' + filetype);
here is my answer.God bless Marc B abundantly.
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
int BUFFER_SIZE = 4096;
try {
int cert_code= jTable1.getSelectedRow();
String tableClick=(jTable1.getModel().getValueAt(cert_code,3).toString());
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee_certificate","root","");
String sql= "SELECT cert, cert_name FROM certificate WHERE cert_code =?" ;
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, tableClick);
ResultSet rs=pstmt.executeQuery();
if(rs.next()){
String filename = rs.getString("cert_name");
Blob blob = rs.getBlob("cert");
InputStream inputStream = blob.getBinaryStream();
String filePath ="D:\\sch work\\skirt\\"+filename;
OutputStream outputStream = new FileOutputStream(filePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
//JOptionPane.showMessageDialog(null,"file saved")
} }
catch (Exception e)
{JOptionPane.showMessageDialog(null,e);}
}

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();
}

File writing with blob data

I am reading the blob data from Oracle database & writing it to a text file. I have two column in my database called Number & system. I have 100 counts in my table. But only the last row is writing in my text row. below is the code I have tried.
rs =stmt.executeQuery("select Number, system from system");
Blob lob = null;
while (rs.next()) {
String RECID = rs.getString(1);
System.out.println("Number"+ Number);
lob=rs.getBlob("system");
byte[] bdata = lob.getBytes(1, (int) lob.length());
String text = new String(bdata);
System.out.println("text"+ text);
System.out.println("rs value"+ lob);
String test=null;
test=RECID+":"+text;
FileOutputStream fos = new FileOutputStream("C:/DataRead/system.txt");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeBytes(test);
dos.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
In text file i am getting 100th record only other 99 rows are not writing.
You are replacing existing text each time in your while loop.
Try this:
FileOutputStream fos = new FileOutputStream("C:/DataRead/system.txt");
DataOutputStream dos = new DataOutputStream(fos);
while (rs.next()) {
String RECID = rs.getString(1);
System.out.println("Number"+ Number);
lob=rs.getBlob("system");
byte[] bdata = lob.getBytes(1, (int) lob.length());
String text = new String(bdata);
System.out.println("text"+ text);
System.out.println("rs value"+ lob);
String test=null;
test=RECID+":"+text;
dos.writeBytes(test+"\n");
}
dos.close();
Replace the line in your code
FileOutputStream fos = new FileOutputStream("C:/DataRead/system.txt");
With:
FileOutputStream fos = new FileOutputStream("C:/DataRead/system.txt", true);

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

Categories

Resources