How to put byte stream image data into JSON object? - java

I want to put multiple images in JSON object using byte stream format, i wrote the following code.
FileInputStream fin = new FileInputStream(pathToImages+"//"+"01.jpg");
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0; ;
sun.misc.BASE64Encoder encoder= new sun.misc.BASE64Encoder();
byte[] contents = new byte[5000000];
int bytesRead = 0;
String strFileContents;
while ((bytesRead = bin.read(contents)) != -1) {
bout.write(encoder.encode(contents).getBytes());
}
JsonObject myObj = new JsonObject();
I want to put encoded byte stream in myObj,but dont know how to do it.
Thanks

JSONObject myObj = new JSONObject();
myObj.put("1",encoder.encode(contents).getBytes());
I think this will work.

Assuming you are using Java 8, and the javax.json package:
Path path = Paths.get(pathToImages, "01.jpg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream(
(int) (Files.size(path) * 4 / 3 + 4));
try (OutputStream base64Stream = Base64.getEncoder().wrap(bytes)) {
Files.copy(path, base64Stream);
}
String base64 = bytes.toString("US-ASCII");
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add("data", base64);
JsonObject myObj = builder.build();

Related

Creating corrupted PDF from bytearray

I was trying to generate PDf from byte array in Java which was returned through webservice, But the PDF cannot be opened. It shows its corrupted, I have attached my code. Anyone pls help about where i got wrong?
JSONObject o = new JSONObject(outjson);
JSONObject jsonob = o.optJSONObject("PDF details");
byte[] pdfbyte=jsonob.optString("pdf bytearray").toString().getBytes();
String str1 = new String(pdfbyte);
File someFile = new File("C:/Users/acer/Desktop/test1.pdf");
FileOutputStream fos = new FileOutputStream(someFile);
byte[] byteData = str1.getBytes();
byte[] byteData1 = test.getBytes();
fos.write(pdfbyte);
fos.flush();
fos.close();
Following is my JSON from webservice:
{"PDF details": {
"id":"121",
"pdf bytearray":"[B#62a58cd"
}
}
Following is my webservice code which outputs bytearray in json:
public Response getPdf( )
{
String flag=null;
File file = new File("C:/Users/acer/Desktop/Report.pdf");
FileInputStream fileInputStream;
byte[] data = null;
byte[] finalData = null;
ByteArrayOutputStream byteArrayOutputStream = null;
fileInputStream = new FileInputStream(file);
data = new byte[(int)file.length()];
finalData = new byte[(int)file.length()];
byteArrayOutputStream = new ByteArrayOutputStream();
fileInputStream.read(data);
byteArrayOutputStream.write(data);
finalData = byteArrayOutputStream.toByteArray();
fileInputStream.close();
System.out.println(finalData);
JSONObject jsonObject = new JSONObject();
JSONObject mainjsonObject = new JSONObject();
jsonObject.put("id","121");
jsonObject.put("pdf bytearray",finalData);
mainjsonObject.put("PDF details",jsonObject);
flag = "" + mainjsonObject;
return Response.status(200).entity(flag).build();
}
i got it right with following chnge in my webservice:
public Response getPdf( )
{
String flag=null;
File file = new File("C:/Users/acer/Desktop/Report.pdf");
FileInputStream fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
fileInputStreamReader.read(bytes);
String encodedBase64 = new String(Base64.encodeBase64(bytes));
JSONObject jsonObject = new JSONObject();
JSONObject mainjsonObject = new JSONObject();
jsonObject.put("id","121");
jsonObject.put("pdf bytearray",encodedBase64);
mainjsonObject.put("PDF details",jsonObject);
flag = "" + mainjsonObject;
return Response.status(200).entity(flag).build();
}
my Client:
String encodedBase64=jsonob.optString("pdf bytearray");
byte[] decodedBytes = Base64.decodeBase64(encodedBase64);
System.out.println("decbyte "+decodedBytes);
File someFile = new File("C:/Users/acer/Desktop/test.pdf");
OutputStream fos = new FileOutputStream(someFile);
fos.write(decodedBytes);
fos.flush();
fos.close();

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

Convert ZIP to byte array without saving the output to file

I have a ZIP file and when I convert it into byte array and encode it, I am unable to print the encoded format without writing it into file.
Could anyone help in solving this issue?
My code is
InputStream is = null;
OutputStream os = null;
is = new FileInputStream("C:/Users/DarkHorse/Desktop/WebServicesTesting/PolicyCredit.zip");
os = new FileOutputStream("D:/EclipseTestingFolder/EncodedFile1.txt");
int bytesRead = 0;
int chunkSize = 10000000;
byte[] chunk = new byte[chunkSize];
while ((bytesRead = is.read(chunk)) > 0)
{
byte[] ba = new byte[bytesRead];
for(int i=0;i<ba.length;i++)
{
ba[i] = chunk[i];
}
byte[] encStr = Base64.encodeBase64(ba);
os.write(encStr);
}
os.close();
is.close();
}
My Output in the file is
UEsDBBQAAAAIANGL/UboGxdAAQUAAK0WAAAQAAAAUG9saWN5Q3JlZGl0LnhtbJVY3Y6rNhC+r9R34AlqSPankSwkdtNskbLZKOk5Va8QC95d6wRIDZyeffszxgSMGUPKFcx8M/b8egwN87IWcZ6waF+cePLp//qLAw/d8BOL/mRxykRL6sk89T1KLq8adx1XLHp5i55YzkRc8SL3F6534y69O0oQpia6K6LiLTqwpBBpKdUPCRq
But when I am trying to print it on the screen, I am getting in this way
8569115686666816565656573657871764785981117112010065658185656575488765656581656565658571571159787785381517410890711084876110104116987486895189541147810467431145782515265108113838097110107831191071001167811510798769075791075386975681675753100541198273689012110110210211512212010383777185807570991205677479856101103119785655738799905411997704399101807611247471137665119471005666797647109821201211078276
You need to create a string representation of Base 64 encoded data.
System.out.println( new String(encStr, Charset.forName("UTF-8")));
Here are some other examples Base 64 Print Question
String Class
Assuming your result array byte[] encStr = Base64.encodeBase64(ba) is actually the encoded string, try the following:
System.out.println(new String(bytes, Charset.defaultCharset());
If you are using JDK 7 you can use Files.readAllBytes(path)
Your code would be much simpler like below:
Path path = Paths.get("C:/Users/DarkHorse/Desktop/WebServicesTesting/PolicyCredit.zip");
byte[] data = Files.readAllBytes(path);
byte[] encStr = Base64.encodeBase64(data);
System.out.println( new String(encStr));
Your will be able to print on console.

Need to improve performance in file unzipping from DB

I am getting zipped blob from db and using that blob in below way,
Ex:-
byte[] inputBlob = blobfile.getBytes(1, (int) blobfile.length());
After getting the blob, the way i got the zippedStream and passed it into another Class method(unzipper).
Ex:-
ByteArrayOutputStream zippedStream = null;
InputStream byteInputStream = null;
IParser parser = null;
byte[] buffer = null;
try {
zippedStream = new ByteArrayOutputStream();
byteInputStream = new ByteArrayInputStream(blob);
blob = null;
int bytes_read;
buffer = new byte[byteInputStream.available()];
while ((bytes_read = byteInputStream.read(buffer)) > 0) {
zippedStream.write(buffer, 0, bytes_read);
}
buffer = null;
byteInputStream.close();
byteInputStream = null;
}catch(Exception e){
e.printStackTrace();
}
unzipper method:
Ex:-
byte[] buffer = new byte[1024];
try {
InputStream decodedInput = new ByteArrayInputStream(zippedStream.toByteArray());
zippedStream.close();
zippedStream = null;
GZIPInputStream unzippedStream = new GZIPInputStream(decodedInput);
decodedInput.close();
decodedInput = null;
int bytes_read;
unzippedOutputstream = new ByteArrayOutputStream();
while ((bytes_read = unzippedStream.read(buffer)) > 0) {
unzippedOutputstream.write(buffer, 0, bytes_read);
}
buffer = null;
unzippedStream.close();
unzippedStream = null;
} catch (Exception ex) {
logger.setException(ex);
logger.error("unzipper", generateMsg("Exception occurred"));
}
Using this way my application got stucked some time, and performance was so bad.
Is there any optimize way to get the zippedstream file and unzipping that easily?
Is all this buffering really needed. Can you IParser parse a Stream?
InputStream zippedStream = ...
IParser parser = ...
parser.parse(new GZIPInputStream(zippedStream));
This will read compressed data, uncompressing as it goes which is much more efficient.

Convert ArrayList to byte array

I have a code where I am converting array list to byte array and then saving that byte array as a BLOB in MySQL database. Below is code:-
Object temp = attributes.get(columnName);
if (temp instanceof List && temp != null) {
List extraAttributes = (ArrayList) temp;
resultStmt.setBytes(currentIndex, createByteArray(extraAttributes));
The method createByteArray is defined as below:
private byte [] createByteArray( Object obj)
{
byte [] bArray = null;
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream objOstream = new ObjectOutputStream(baos);
objOstream.writeObject(obj);
bArray = baos.toByteArray();
}
catch (Exception e)
{
TraceDbLog.writeError("Problem in createByteArray", e);
}
return bArray;
}
Well the above code was written earlier for writing HashMap to BLOB i am using same for converting ArrayList if HashMap to BLOB.
The problem which is occurring in read code when i am reading the blob.
private Object readBytes (ResultSet rs, String columnName)
throws SQLException
{
ObjectInputStream ois = null;
byte [] newArray;
Object obj = null;
try
{
newArray = rs.getBytes(columnName);
ois = new ObjectInputStream (new ByteArrayInputStream(newArray));
obj = ois.readObject ();
}
In the read part the object is not coming as arrayList of hasMap and in debug perspective in eclipse eclipse is also not able to inspect the object which is coming.
I have also tried typecasting the object to List but still no success in getting the right response.
Please tell me whether there is any flaw in reading/writing the above BLOB.
I have added sample coding for convert ArrayList to byte[].
One reasonable way would be to use UTF-8 encoding like DataOutputStream does for each string in the list. For a string it writes 2 bytes for the length of the UTF-8 encoding followed by the UTF-8 bytes.
This would be portable if you're not using Java on the other end. Here's an example of encoding and decoding an ArrayList:
// example input list
List<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
list.add("baz");
// write to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
for (String element : list) {
out.writeUTF(element);
}
byte[] bytes = baos.toByteArray();
// read from byte array
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
DataInputStream in = new DataInputStream(bais);
while (in.available() > 0) {
String element = in.readUTF();
System.out.println(element);
}
The easiest way is to convert it to json string and then to bytes
Gson gson = new Gson();
Type type = new TypeToken<List<Alarm>>() {}.getType();
String json = gson.toJson(list, type);
byte[] bytes = json.getBytes();

Categories

Resources