如何通过 JSON in ANDROID 在网络数据库中保存和检索图像

How to save and retrieve image in a web database thru JSON in ANDROID

我正在尝试使用 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);

但是没有生成图片是怎么回事?

提前致谢

我在这个 post that I did a couple of days ago and the recommendation they gave me was to use a networking library like Google Volley to make my requests more easier and it's way less work. Also, here is a link 教程中遇到了一个非常相似的问题,该教程由自定义 ListView 以及使用 Volley 的图像和文本组成。

希望对您有所帮助。