inserting image to sqlite - java

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

Related

Convert blob to string to to create a json object and then change the string back to blob

My requirement is to convert the blob in a database field to string to create a json object. I have achieved that.
Now, I need to convert this string back to blob. I wrote the below code. But, it does not work. In my instance, I have the word document stored as blob. I converted it to string but when I converted the string to blob, the document does not open properly.
Please let me know a way to convert the string back to blob.
DocumentTemplateKey documentTemplateKey = new DocumentTemplateKey();
documentTemplateKey.documentTemplateID = "XX";
DocumentTemplateDtls documentTemplateDtls = DocumentTemplateFactory.newInstance().read(documentTemplateKey);
byte[] blobAsBytes = documentTemplateDtls.contents.copyBytes();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(blobAsBytes, 0, blobAsBytes.length);
String pdfBase64String =
org.apache.commons.codec.binary.StringUtils.newStringUtf8(org.apache.
commons.codec.binary.Base64.encodeBase64(bos.toByteArray()));
OutputStreamWriter out = new OutputStreamWriter(System.out);
JsonWriter writer = new JsonWriter(out);
//set indentation for pretty print
writer.setIndent("\t");
//start writing
writer.beginObject(); //{
writer.name("blob").value(pdfBase64String);
byte[] stringAsBytes = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(pdfBase64String);
Blob blob = new Blob(stringAsBytes);
documentTemplateDtls.contents = blob;
documentTemplateDtls.documentTemplateID = "XX12";
documentTemplateDtls.name = "XX12";
DocumentTemplateFactory.newInstance().insert(documentTemplateDtls);
writer.endObject();
writer.flush();
//close writer
writer.close();
Here's your problem:
byte[] stringAsBytes = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(pdfBase64String);
You're getting the bytes of your base64 string, but you ought to be putting it through a base64 decoder.

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

Base91 string corruption in mysql database

I'm using Base91 to store an image as a String in a mysql database. When I retrieve the string to convert it back to an image, the string seems to have been corrupted by the database.
I'm sure it's being corrupted in the database because I did an isolated test on a single device of taking a picture, converting it to a Base91 byte[], converting the byte[] to a string (using Latin1), converting the string back to byte[], then to an image, and it worked. When I try that with a server in the middle, the images end up broken.
I've tried changing the collation on the specific column on the database from utf8 to ascii to latin1, no luck.
Code:
Encoding Picture:
File file1 = new File(path);
FileInputStream in = new FileInputStream(file1);
byte[] imagesBytes = new byte[(int) file1.length()];
in.read(imagesBytes, 0, (int) file1.length());
_picture = new String(Base91.encode(imagesBytes), Base91.CHARSET);
//appointment.addPicture(new String(Base91.encode(imagesBytes), Base91.CHARSET));
Storing encoded image:
JsonObject jsonx = new JsonObject();
jsonx.addProperty("picture", request.getParameter("picture"));
db.insert("AppointmentPicture",
"(AppointmentID, picture)values(?,?)",
new Object[]{appointment.getDbID(), jsonx.toString()},
false);
Retrieving the image:
ResultSet rSet = db.query("AppointmentPicture", new String[]{"picture"}, "AppointmentID = ?", new Object[]{appointmentID});
System.out.println("pictures grabbed");
JsonObject json = new JsonObject();
int counter = 0;
while (rSet.next()) {
counter++;
json.addProperty(String.valueOf(counter), rSet.getString("picture"));
}
json.addProperty("count", String.valueOf(counter));
response.getWriter().write(json.toString());
System.out.println("pictures returned");
Decoding Image:
String serverResponse = in.readLine();
JSONObject json = new JSONObject(serverResponse);
int count = Integer.parseInt(json.getString("count"));
for(int i = 0; i < count; i++){
JSONObject j = new JSONObject(json.getString(String.valueOf(i + 1)));
byte[] picBytes = j.getString("picture").getBytes(Base91.CHARSET);
File file = new File(imageDirectory, String.valueOf(System.currentTimeMillis()) + ".jpeg");
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
out.write(picBytes, 0, picBytes.length);
}

Trying to insert Base64 image to sql server database

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

To display a Base64 image in AngularJS

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}}">

Categories

Resources