Reputation: 503
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);
}
Upvotes: 0
Views: 243