【发布时间】:2015-03-05 14:44:51
【问题描述】:
我正在尝试使用 JSON 将图像保存和检索到我的 Web 数据库,但似乎我做得不对,问题是图像没有被复制。这是我的代码
获取图片
BitmapDrawable bitmapDrawable = ((BitmapDrawable)objectImage.getDrawable());
Bitmap b = bitmapDrawable.getBitmap();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] img = bos.toByteArray();
在此之后,我希望图像现在在 byte[] 数组中被压缩或加密,现在这是我通过 JSON 在我的数据库中传递它的方式
String imgData = Base64.encodeToString(image, Base64.DEFAULT);
nameValuePairs.add(new BasicNameValuePair("image", imgData));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(getUri(category));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
这就是我检索它的方式
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(getUriForRetrieve(category));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
} catch (Exception e) {
Log.e("log_tag", "getProducts()" + e.toString());
}
return result;
}
try {
JSONArray jArray = new JSONArray(getResult("Letters"));
JSONObject json_data = null;
if (jArray.length() > 0) {
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
Letters letter = new Letters();
letter.setImage(Base64.decode(json_data.getString("image"),
Base64.DEFAULT));
letterList.add(letter);
}
}
} catch (JSONException e1) {
Log.e("log_tag", "getProducts()" + e1.toString());
} catch (ParseException e1) {
e1.printStackTrace();
}
这是我如何将其解码为位图
Bitmap b1 = BitmapFactory.decodeByteArray(img, 0, img.length);
objectImage.setImageBitmap(b1);
但是没有生成图片有什么问题?
提前致谢
【问题讨论】:
-
我强烈建议您以这种方式将图像发送到您的服务器。 JSON 并不意味着包含您的
Base64.encodeToString(image, Base64.DEFAULT);将创建的潜在巨大长度。您还会发现许多 JSON 解码器对于它们将解析的 JSON 内容都有一个最大大小。一个更好的方法是使用MultipartEntityBuilder并将您的文件作为FileBody和您的其他JSON 元素作为TextBody发送(假设您使用的是apacheHTTPClient。 -
只是用一些事实来支持我的评论,看看这个问题:stackoverflow.com/questions/1262376/… 和这个评论:基于msdn.microsoft.com/en-us/library/…
The maximum length of JSON strings. The default is 2097152 characters, which is equivalent to 4 MB of Unicode string data. -
我能够解决这个问题,但我不会推荐它,因为您需要很长时间才能检索到您的图像。
标签: android json database bitmap bytearray