简体   繁体   English

如何在 android 中使用解析 api 在解析服务器中上传图像

[英]How to upload an image in parse server using parse api in android

I want to upload an image in parse cloud server in android.我想在 android 的解析云服务器中上传图像。 But I am unable to do so.但我无法这样做。

I have tried the following code:我尝试了以下代码:

Drawable drawable = getResources().getDrawable(R.drawable.profilepic) ;
Bitmap bitmap = (Bitmap)(Bitmap)drawable()
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] data = stream.toByteArray();                

ParseFile imageFile = new ParseFile("image.png", data);
imageFile.saveInBackground();

Please let me know how can I do it.请让我知道我该怎么做。

After struggling for several hours here is code segment works for me.经过几个小时的努力,这里的代码段对我有用。

1. Data Member of activity class 1.活动类的数据成员

Bitmap bmp;
Intent i;
Uri BmpFileName = null;

2. Starting the camera. 2. 启动相机。 Goal is to start camera activity and BmpFileName to store the referrence to file目标是启动相机活动和 BmpFileName 以存储对文件的引用

String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {

String path = Environment.getExternalStorageDirectory().getName() + File.separatorChar + "Android/data/" + this.getPackageName() + "/files/" + "Doc1" + ".jpg";

File photoFile = new File(path);
try {
if (photoFile.exists() == false) { 
photoFile.getParentFile().mkdirs();
photoFile.createNewFile();
}
} 
catch (IOException e) 
{
Log.e("DocumentActivity", "Could not create file.", e);
}
Log.i("DocumentActivity", path);
BmpFileName = Uri.fromFile(photoFile);
i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, BmpFileName);
startActivityForResult(i, 0);

3. Reading contents from Camera output by overriding onActivityResult. 3.通过覆盖onActivityResult从Camera输出中读取内容。 Goal is to get bmp variable valuated.目标是评估 bmp 变量。

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
bmp = MediaStore.Images.Media.getBitmap( this.getContentResolver(), BmpFileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {

// TODO Auto-generated catch block
e.printStackTrace();
}
// Myocode to display image on UI - You can ignore
if (bmp != null)
IV.setImageBitmap(bmp);
}
}

4. On Save event 4. 保存事件

// MUST ENSURE THAT YOU INITIALIZE PARSE
Parse.initialize(mContext, "Key1", "Key2");

ParseObject pObj = null;
ParseFile pFile = null ;
pObj = new ParseObject ("Document");
pObj.put("Notes", "Some Value");

// Ensure bmp has value
if (bmp == null || BmpFileName == null) {
Log.d ("Error" , "Problem with image"
return;
}

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100, stream);
pFile = new ParseFile("DocImage.jpg", stream.toByteArray());
try 
{
pFile.save();
pObj.put("FileName", pFile);
pObj.save();
_mParse.DisplayMessage("Image Saved");
} 
catch (ParseException e) 
{
// TODO Auto-generated catch block
_mParse.DisplayMessage("Error in saving image");
e.printStackTrace();
}

// Finish activity in my case . // 在我的情况下完成活动。 you may choose some thing else finish();你可以选择其他的东西finish();

So here are key difference from others所以这是与其他人的主要区别

  • I called initialize parse.我调用了初始化解析。 You may laugh about it but folks have spent hour's debugging code without realize that parse was not initialized您可能会对此一笑置之,但人们已经花了几个小时调试代码,却没有意识到 parse 没有初始化
  • Use Save instead of SaveInBackground.使用 Save 而不是 SaveInBackground。 I understand that it may hold the activity but that is desired behavior for me and more importantly it works我知道它可能会举行活动,但这对我来说是理想的行为,更重要的是它有效

Let me know if it does not work让我知道它是否不起作用

Save ParseObject in the background在后台保存 ParseObject

 // ParseObject ParseObject pObject = new ParseObject("ExampleObject"); pObject.put("myNumber", number); pObject.put("myString", name); pObject.saveInBackground(); // asynchronous, no callback

Save in the background with callback使用回调在后台保存

pObject.saveInBackground(new SaveCallback () { @Override public void done(ParseException ex) { if (ex == null) { isSaved = true; } else { // Failed isSaved = false; } } });

Variations of the save...() method include the following: save...() 方法的变体包括:

 saveAllinBackground() saves a ParseObject with or without a callback. saveAll(List<ParseObject> objects) saves a list of ParseObjects. saveAllinBackground(List<ParseObject> objects) saves a list of ParseObjects in the background. saveEventually() lets you save a data object to the server at some point in the future; use this method if the Parse cloud is not currently accessible.

Once a ParseObject has been successfully saved on the Cloud, it is assigned a unique Object-ID.一旦 ParseObject 成功保存在云上,它就会被分配一个唯一的 Object-ID。 This Object-ID is very important as it uniquely identifies that ParseObject instance.这个 Object-ID 非常重要,因为它唯一地标识了 ParseObject 实例。 You would use the Object-ID, for example, to determine if the object was successfully saved on the cloud, for retrieving and refreshing a given Parse object instance, and for deleting a particular ParseObject.例如,您将使用 Object-ID 来确定对象是否已成功保存在云中、检索和刷新给定的 Parse 对象实例以及删除特定的 ParseObject。

I hope you will solve your problem..我希望你能解决你的问题..

Parse.initialize(this, "applicationId", "clientKey");

     byte[] data = "Sample".getBytes();    //data of your image file comes here

     final ParseFile file = new ParseFile(data);
     try {
        file.save();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     if (file.isDirty()){
                     //exception or error message etc 
     }
     else{

         try {
            ParseUser.logIn("username", "password");    //skip this if already logged in
        } catch (ParseException e2) {
            e2.printStackTrace();
        }
         ParseObject userDisplayImage = new ParseObject("UserDisplayImage");
            user = ParseUser.getCurrentUser();
            userDisplayImage.put("user", user);     //The logged in User
            userDisplayImage.put("displayImage", file); //The image saved previously
            try {
                userDisplayImage.save();      //image and user object saved in a new table. Check data browser
            } catch (ParseException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

         //See how to retrieve

         ParseQuery query = new ParseQuery("UserDisplayImage");
         query.whereEqualTo("user", user);
         try {
            parseObject = query.getFirst();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         ParseFile imageFile = null;
          imageFile = parseObject.getParseFile("displayImage");
          try {
            byte[] imgData = imageFile.getData(); //your image data!!
        } catch (ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

     }

Use it like this像这样使用它

 //Convert Bitmap to Byte array --For Saving Image to Parse Db. */

 Bitmap profileImage= "your bitmap";

 ByteArrayOutputStream blob = new ByteArrayOutputStream();

 profileImage.compress(CompressFormat.PNG, 0 /* ignored for PNG */,blob);

 imgArray = blob.toByteArray();

 //Assign Byte array to ParseFile
 parseImagefile = new ParseFile("profile_pic.png", imgArray);

 parseUser.getCurrentUser().put("columname in parse db", parseImagefile);
 parseUser.getCurrentUser().saveInBackground();

I hope this will help you..我希望这能帮到您..

Simple code of Imageupload and retriving using Glide to parse. Imageupload 和 retriving 的简单代码使用 Glide 进行解析。

Image Upload图片上传

destination_profile is File object of you want to upload image path. destination_profile是您要上传图像路径的文件对象。

    ParseUser currentUser = ParseUser.getCurrentUser();
    if (destination_profile != null) {
            Glide.with(getActivity()).load(destination_profile.getAbsolutePath()).asBitmap().toBytes().centerCrop().into(new SimpleTarget<byte[]>() {
                @Override
                public void onResourceReady(byte[] resource, GlideAnimation<? super byte[]> glideAnimation) {


                    final ParseFile parseFile = new ParseFile(destination_profile.getName(), resource);
                    parseFile.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            currentUser.put("picture", parseFile);
                            currentUser.saveInBackground(new SaveCallback() {
                                @Override
                                public void done(ParseException e) {
                                    showToast("Profile image upload success");
                                }
                            });
                        }
                    });


                }
            });
        }

Image Retriving图像检索

img_userProfilePicture_bg is boject of ImageView where you want to set image. img_userProfilePicture_bg是您要设置图像的 ImageView 的对象。

    ParseUser currentUser = ParseUser.getCurrentUser();
    if (currentUser.has("picture")) {
        ParseFile imageFile = (ParseFile) currentUser.get("picture");
        imageFile.getDataInBackground(new GetDataCallback() {
            public void done(final byte[] data, ParseException e) {
                if (e == null) {

                    Glide.with(getActivity()).load(data).centerCrop().into(img_userProfilePicture_bg);

                } else {
                    // something went wrong
                }
            }
        });
    }

Assuming you have your bitmap file bitmap .假设你有你的位图文件bitmap

    ParseObject object = new ParseObject("NameOfClass");

    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    byte[] scaledData = stream.toByteArray();

    ParseFile image = new ParseFile("image.jpeg",scaledData);
    image.saveInBackground(new SaveCallback() {
        @Override
        public void done(ParseException e) {
            if (e==null)
                //Image has been saved as a parse file.
            else
                //Failed to save the image as parse file.
        }
    });

    object.put("images",image);
    object.saveInBackground(new SaveCallback() {
        @Override
        public void done(ParseException e) {
            if (e==null)
                //Image has been successfuly uploaded to Parse Server.
            else
                //Error Occured.
        }
    });

It is important to convert the Bitmap into byte[] and then uploading the Parse File before associating it with the Parse Object.将 Bitmap 转换为byte[]并在将 Parse File 与 Parse Object 关联之前上传 Parse 文件非常重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM