NewBieAndroid
NewBieAndroid

Reputation: 43

Saving jpg file with cloud-code Parse-Server

I'm trying to save jpg files with cloud code on parse server ...

On Android I can do it using this way

Bitmap bitmap = ((BitmapDrawable) myImageView.getDrawable()).getBitmap();

ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                    byte [] byteArrayPhotoUpdate = stream.toByteArray();
                    final ParseFile pictureFileParse = new ParseFile( newUserInfo.getObjectId() + ".JPEG",byteArrayPhotoUpdate);

     newUserInfo.put("profile_picture",pictureFileParse);
     newUserInfo.saveInBackground();

But I have no idea how to do this in the cloud code. I call my cloud code functions like this

HashMap<String, String> params = new HashMap();

ParseCloud.callFunctionInBackground("myCloudFuncion", params, new FunctionCallback<String>() {
         @Override
          public void done(String aFloat, ParseException e) {

                }
            }); 

but I have no idea how to pass a bitmap in hashmap params. I already searched the internet, but nothing that I found in helped, the links that refer to something useful, is already old and outdated, from the epoch of the old parse ...

In parse docs I found this

    var base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=";
    var file = new Parse.File("myfile.txt", { base64: base64 });

Which made me confused because I do not know if the 2 "base64" parameters refer to variable or base64 type

Should I convert my bitmap to base64 and send it as parameter to the cloud code?

If you have been through this and know how, I will be very happy to know your solution. Thank you!

Upvotes: 4

Views: 1147

Answers (2)

user6925031
user6925031

Reputation: 36

This answer works if you do not wish to use Base64 that requires API 26 and above for android.

I know João Armando has answered this question, but this is for the benefit of others who, like me, are supporting versions before API 26 for Android.

P.S. The Base64.encodeBase64(...) is deprecated and Base64.getEncoder()... is used now, which requires API 26.

There are 3 key parts to the solution:

  1. Convert your bitmap to byteArray
  2. Send this byteArray directly as params when calling your cloud function
  3. Format this byteArray in cloud code itself

In Android:

Convert bitmap to byte[]

Bitmap bitmap = <Your source>;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Send as params when calling cloud function

HashMap<String, Object> params = new HashMap<>();
params.put("imageInByteArray", byteArray);

ParseCloud.callFunctionInBackground("yourCloudFunction", params, new FunctionCallback<Map>() {
  @Override
  public void done(Map object, ParseException e) {
     if(e == null){
       // Success
     } else {
       // Failed
     }
  }
});

In cloud function/code

Depends on the version of javascript you use, the codes may differ. I am using a backend-as-a-service provider, which has improved from promises-related codes. The logic should still be applicable regardless.

Parse.Cloud.define("reportId", async request => {
  // Retrieve and set values from client app
  const imageInByteArray = request.params.imageInByteArray;

  // Format as ParseFile
  var file = new Parse.File("image.png", imageInByteArray);

  // Initialize your class, etc.
  ....

  // Save your object
  await yourImageObject.save(null, {useMasterKey:true});

});

Upvotes: 1

Jo&#227;o Armando
Jo&#227;o Armando

Reputation: 167

you need convert your image bitmap for base64 like that:

            Bitmap bitmap = ((BitmapDrawable) img.getDrawable()).getBitmap();

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte [] byteArrayPhotoUpdate = stream.toByteArray();
            String encodedfile = new String(Base64.encodeBase64(byteArrayPhotoUpdate), "UTF-8");

And then, send your string base64 in params, like that:

 HashMap<String, String> params = new HashMap();
 params.put("fileInfo",encodedfile);
 ParseCloud.callFunctionInBackground("saveParseUserInfo", params, new FunctionCallback<String>() {
                    @Override
                    public void done(String aFloat, ParseException e) {

                     Log.i("ewaeaweaweaweawe", "done: " + aFloat);
                    }
                });

Now in your cloud code, use that:

Parse.Cloud.define("saveParseUserInfo", function(request, response) {
                var userId = request.user.id;
                var base64 = request.params.fileInfo;
                var userClass = Parse.Object.extend("User");
                //create a user object to set ACL
                var userObject = userClass.createWithoutData(userId);

                //create new ParseObject
                var userPublicClass = Parse.Object.extend("userPublic");
                var userPublic = new userPublicClass();
                var aclAction = new Parse.ACL(userObject);
                aclAction.setPublicReadAccess(true);
                userPublic.setACL(aclAction);
                userPublic.set("name", "name random");
                userPublic.set("username", "username_random");
                //Now create a Parse File object
                var file = new Parse.File("photo.jpeg", { base64: base64 });
                //set file object in a colum profile_picture
                userPublic.set("profile_picture",file);
                //save
                userPublic.save(null, { useMasterKey: true,  
                success: function(actionSuccess) {  

                    response.success("saved!!");
                },
                error: function(action, error) {
                    // Execute any logic that should take place if the save fails.
                    // error is a Parse.Error with an error code and message.
                response.error(error.message);
            }
            });






            });     

I hope it's help you.

Upvotes: 2

Related Questions