开发者

Upload a base64 converted image on server in android

开发者 https://www.devze.com 2023-02-21 01:47 出处:网络
I need to convert the Image in base64 format and then upload it on开发者_C百科 server and then retrieve the base64 string from the server and convert it back to image... How to do it?First Convert Bit

I need to convert the Image in base64 format and then upload it on开发者_C百科 server and then retrieve the base64 string from the server and convert it back to image... How to do it?


First Convert Bitmap to 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);

Then Upload with Json Object as Below:

        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();

Then You can retrieve these Base 64 string on Your Response.

And then Convert these Base64 to bitmap by Below:

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

Then use these bitmap in Your Image View.


This post was made by someone wanting to go the opposite direction you're going, but the answers are still relevant:

converting base64 String to image in android

Beware of out of memory problems:

OutOfMemoryError: bitmap size exceeds VM budget :- Android

Here's an example of posting a file to a server from an Android app:

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


Use this link and get the Base64Coder class . This will help you to Encode Image into Base64 String and Decode the String into byte array.You can make Image file by using that bytes.

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


    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
0

精彩评论

暂无评论...
验证码 换一张
取 消