//Convert binary image file to byte array to base64 encoded string
FileInputStream mFileInputStream = new FileInputStream("C:\\basicsworkspace\\base64upload\\src\\main\\resources\\basic.png");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int bytesRead = 0;
while ((bytesRead = mFileInputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] ba = bos.toByteArray();
byte[] encoded = Base64.getEncoder().encode(ba);
connection = DriverManager.getConnection(connectionString);
String insertSql = "INSERT INTO test (image) VALUES "
+ "("+encoded+")";
System.out.println(insertSql);
prepsInsertProduct = connection.prepareStatement(
insertSql);
System.out.println(prepsInsertProduct.execute());
Trying to insert image to sql server and need to have the image as base64 format. I am getting below exception. Please let me know what type of datatype and how to insert image as base64 in sql server.
Output :
INSERT INTO test (image) VALUES ([B#7229724f)
java.sql.SQLException: Invalid SQL statement or JDBC escape, terminating ']' not found.
at net.sourceforge.jtds.jdbc.SQLParser.parse(SQLParser.java:1270)
at net.sourceforge.jtds.jdbc.SQLParser.parse(SQLParser.java:165)
at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.<init>(JtdsPreparedStatement.java:111)
at net.sourceforge.jtds.jdbc.JtdsConnection.prepareStatement(JtdsConnection.java:2492)
at net.sourceforge.jtds.jdbc.JtdsConnection.prepareStatement(JtdsConnection.java:2450)
at base64upload.base64upload.App.main(App.java:70)
You are just concatenating string with toString() value of byte array. That's incorrect. You should use another approach:
String insertSql = "INSERT INTO test (image) VALUES (?)";
System.out.println(insertSql);
prepsInsertProduct = connection.prepareStatement(insertSql);
// here set your array
prepsInsertProduct.setBytes(encoded);
Related
I want to insert an image in a DB row in blob format, after encrypting it, using a Prepared Statement in Java. I'm using a custom encryption function and a corresponding decryption function is used on the other end to decrypt the blob back into an image (I'm not involved with the decryption part, only the encryption). The problem is that the image after the decryption is not the original one. It is a very small white image, so I assume something in my process is incorrect and I would really appreciate any feedback or thoughts. Here is the code:
// already existing code
...
String photo_str // contains the photo
int id = 1; // for this example
byte[] blobBytes = new sun.misc.BASE64Decoder().decodeBuffer(photo_str);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(blobBytes));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ImageIO.write(image, type, stream);
input.set(photo_str, stream.toByteArray()); // this sets the photo_str field (String) to the second argument
// my code
byte[] blobBytes = photo_str.getBytes();
byte[] blob = CustomEncrypt(id, blobBytes); // custom encryption function
InputStream targetStream = new ByteArrayInputStream(blob);
String updateString = "UPDATE MY_TABLE SET PHOTO=? WHERE ID=?";
PreparedStatement ps = con.prepareStatement(updateString);
ps.setBlob(1, targetStream, blob.length);
ps.setString(2, id);
int rows = ps.executeUpdate();
I already have the image in a String format, which is the sequence of the bytes in the byte array, as I understand, so the problem lies when I convert to byte array and then write to input stream?
Thank you in advance.
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();
I have inserted a Base64 image to a database using this Java code:
FileInputStream mFileInputStream = new FileInputStream("C:\\basicsworkspace\\base64upload\\src\\main\\resources\\basic.png");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int bytesRead = 0;
while ((bytesRead = mFileInputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] ba = bos.toByteArray();
//byte[] encoded = Base64.getEncoder().encode(ba); // Util
byte[] encoded = Base64.encodeBase64(ba); // Apache
connection = DriverManager.getConnection(connectionString);
String insertSql = "INSERT INTO test (image) VALUES (?)" ;
prepsInsertProduct.setBytes(encoded);
System.out.println(insertSql);
prepsInsertProduct = connection.prepareStatement(insertSql);
System.out.println(prepsInsertProduct.execute());
But if I try to display the image in AngularJS using it, it is not displaying the image. In SQL Server I have saved my image as varbinary(max) and in AngularJS code,
config(function ($compileProvider) {
console.log($compileProvider.imgSrcSanitizationWhitelist());
})
<img src="choice:image/png;base64,{{choice.Icon}}">
But I am getting only bytes with a message like this:
unsafe:choice:image/png;base64,6956424F5277304B47676F414141414E535568455567…
Where am I going wrong? The image is in PNG format.
In POJO I made changes for byte[] and it worked. I have datatype with String and modified to byte[] but Base64 images didn't displayed but t is displaying only byte array images.
Try in your controller:
$scope.choice.Icon = 'data:image/jpeg;base64,' + yourImageData;
And in your HTML content:
<img ng-src="{{choice.Icon}}">
my mission is to change 2 php pages with a java webapp that writes an upload pdf file to a clob and reads it when user ask for a download.
I threated the pdf as a byte array and have been able to read/write it correctly
the big problem is the backward compatibility: files written by php are not readable by my java webapp and vice-versa
thanks in advance for help
NOTE: Do not answer me to use a Blob, I know it is the easy way but in this case we have to assume we cannot make an alter table on the db due to backward compatibility
Here's my code to read the clob into a byte array:
byte[] result = null;
InputStream is = null;
ByteArrayOutputStream bos = null;
//...prepare the query to get clob as first column in the resultset
ResultSet rs = stmt.executeQuery();
int len;
int size = 1024;
byte[] buf;
if(rs.next()) {
is = rs.getBinaryStream(1);
bos = new ByteArrayOutputStream();
buf = new byte[size];
while ((len = is.read(buf, 0, size)) != -1)
bos.write(buf, 0, len);
bos.flush();
bos.close();
is.close();
result = bos.toByteArray();
}
rs.close();
here's the code to write the byte array into clob:
//...some other sql stuff here...
stmt = conn.prepareStatement("SELECT clob_col FROM my_table WHERE prim_key = ? FOR UPDATE");
stmt.setString(1, param);
ResultSet rs = stmt.executeQuery();
Clob myclob=null;
if(rs.next())
myclob=rs.getClob(1);
OutputStream writer = myclob.setAsciiStream(1L);
writer.write(allegato);
writer.flush();
writer.close();
stmt = conn.prepareStatement("UPDATE my_table SET clob_col = ? WHERE prim_key = ? ");
stmt.setClob(1, myclob);
stmt.setString(2, param);
stmt.executeUpdate();
oracle encoding is ITALIAN_ITALY.WE8ISO8859P1
php encoding is ITALIAN_ITALY.UTF8
A possible solution:
write to clob the hex rapresentation of the byte array, and do the same in read phase
the main advantage are
- few changes in php and java
- no changes to db (alter table)
- indipendent from db encoding
in php we use bin2hex and hex2bin functions before to write and after read the clob
in java we implement 2 easy equivalent functions of bin2hex and hex2bin:
public static byte[] HexToBin(String str){
try{
byte[] result=new byte[str.length()/2];
for (int i = 0; i < result.length; i++)
result[i]=(byte) Integer.parseInt(str.substring(2*i, (2*i)+2), 16);
return result;
}catch(Exception x){
x.printStackTrace();
return null;
}
}
public static String BinToHex(byte[] b){
try{
StringBuffer sb=new StringBuffer();
for (byte bb:b) {
String hexStr = String.format("%02x", bb);
sb.append((hexStr.length()<2)?"0":"");
sb.append(hexStr);
}
return sb.toString();
}catch(Exception x){
x.printStackTrace();
return null;
}
}
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