【问题标题】:Upload a base64 converted image on server in android在android中的服务器上上传base64转换后的图像
【发布时间】:2011-07-27 14:49:33
【问题描述】:

我需要将图片转换为base64格式,然后上传到服务器,然后从服务器检索base64字符串并将其转换回图片...怎么做?

【问题讨论】:

标签: android file-upload base64


【解决方案1】:

首先将位图转换为 Base 64

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Bitmap bitmap = Bitmap.createScaledBitmap("Your Bitmap Object Here", 100, 100, false);
    bitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, false);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encoded = Base64.encodeToString(imageBytes, Base64.NO_WRAP);

然后使用 Json 对象上传如下:

        JSONObject jsonObject = new JSONObject();

        String withBase = "data:image/jpeg;base64," + encoded;
        jsonObject.put("b64", "" + withBase);
        System.out.println("base 64 == " + jsonObject.toString());
        return jsonObject.toString();

然后您可以在您的响应中检索这些 Base 64 字符串。

然后通过下面将这些Base64转换为位图:

byte[] decodeString = Base64.decode(encodedImage, Base64.DEFAULT); 位图decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

然后在您的图像视图中使用这些位图。

【讨论】:

    【解决方案2】:

    这篇文章是由想要与你相反的方向发展的人发布的,但答案仍然相关:

    converting base64 String to image in android

    注意内存不足问题:

    OutOfMemoryError: bitmap size exceeds VM budget :- Android

    以下是从 Android 应用向服务器发布文件的示例:

    http://groups.google.com/group/android-developers/browse_thread/thread/e51d4f74452a1143?tvc=2&pli=1

    【讨论】:

      【解决方案3】:

      使用这个link 并获取 Base64Coder 类。这将帮助您将图像编码为 Base64 字符串并将字符串解码为字节数组。您可以使用该字节制作图像文件。

          byte[] stringBytes = your_Base64_String.getBytes();
          byte[] img = null;
          try {
              img = Base64Coder.decode(stringBytes );
          } catch (IOException e) {
               e.printStackTrace();
           }
      

      【讨论】:

        【解决方案4】:
            public String ConvertBitmapToBase64Format(Bitmap bitmap) 
        
           {
        
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 70, stream);
            byte[] byteFormat = stream.toByteArray();
            // get the base 64 string
            String imageString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
            return imageString;
        
           }
        
           // then this imageString pass to json object 
           String encodedImage=ConvertBitmapToBase64Format(bitmap); // pass your image bitmap
        
           JsonObject.put("Key",
                            encodedImage);
        
           pass this jsonObject to your webservice
        

        【讨论】:

          猜你喜欢
          • 2019-09-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多