我正在使用 Base91 将图像作为字符串存储在 mysql 数据库中。当我检索字符串以将其转换回图像时,该字符串似乎已被数据库损坏。
我确定它在数据库中已损坏,因为我在单个设备上进行了单独的拍照测试,将其转换为 Base91 byte[]
,将 转换byte[]
为字符串(使用 Latin1),将字符串转换回byte[]
,然后转换为图像,它的工作。当我尝试在中间使用服务器时,图像最终会损坏。
我尝试将数据库上特定列的排序规则从 utf8 更改为 ascii 到 latin1,但没有运气。
代码:
编码图片:
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));
存储编码图像:
JsonObject jsonx = new JsonObject(); jsonx.addProperty("picture", request.getParameter("picture")); db.insert("AppointmentPicture", "(AppointmentID, picture)values(?,?)", new Object[]{appointment.getDbID(), jsonx.toString()}, false);
检索图像:
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");
解码图像:
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); }