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();
Related
I want to add an image to the database.But nothing happens.There is a connection to the database.
AssetManager assManager = getApplicationContext().getAssets();
AssetFileDescriptor assetFileDescriptor = assManager.openFd("k.jpeg");
FileDescriptor fileDescriptor = assetFileDescriptor.getFileDescriptor();
String newPath = path.toString();
Bitmap bitmap = BitmapFactory.decodeStream(ims);
imageView.setImageBitmap(bitmap);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
byte[] bytesImage = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(bytesImage, Base64.DEFAULT);
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO photo(id) VALUES (?)");
FileInputStream fin = new FileInputStream(fileDescriptor);
preparedStatement.setBinaryStream(1, fin);
//Executing the statement
preparedStatement.executeUpdate()
writes an error
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect string value: '\xC5\x01\xB4\xBF\x0D\x00...' for column 'id' at row
maybe you forget to set connection.
if your connection that's real have not been made.
You can connect to a database using the getConnection() method of the DriverManager class.
Connect to the MySQL database by passing the MySQL URL which is jdbc:mysql://localhost/sampleDB (where sampleDB is the database name), username and password as parameters to the getConnection() method.
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password")
semoga code ini bisa membantu anda
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();
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();
}
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);
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);