【问题标题】:How to upload an image in parse server using parse api in android如何在 android 中使用解析 api 在解析服务器中上传图像
【发布时间】:2013-04-23 22:59:18
【问题描述】:

我想在 android 的解析云服务器中上传一张图片。但我做不到。

我已经尝试了以下代码:

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

请告诉我该怎么做。


我添加了一个赏金来寻找解决这个常见问题的最佳确定代码

【问题讨论】:

    标签: android image parse-platform android-drawable


    【解决方案1】:

    经过几个小时的努力,这里的代码段对我有用。

    1.活动类的数据成员

    Bitmap bmp;
    Intent i;
    Uri BmpFileName = null;
    

    2。启动相机。目标是启动相机活动和 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.通过覆盖 onActivityResult 从相机输出中读取内容。目标是评估 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.保存事件

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

    // 在我的情况下完成活动。你可以选择别的东西 完成();

    所以这是与其他人的主要区别

    • 我调用了初始化解析。你可能会对此一笑置之,但人们已经花了几个小时调试代码,却没有意识到解析没有初始化
    • 使用 Save 而不是 SaveInBackground。我知道它可能会举行活动,但这是我想要的行为,更重要的是它有效

    如果它不起作用,请告诉我

    【讨论】:

      【解决方案2】:

      在后台保存 ParseObject

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

      使用回调保存在后台

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

      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.
      

      一旦 ParseObject 成功保存在云端,它就会被分配一个唯一的 Object-ID。这个 Object-ID 非常重要,因为它唯一地标识了 ParseObject 实例。例如,您可以使用 Object-ID 来确定对象是否已成功保存在云中、检索和刷新给定的 Parse 对象实例以及删除特定的 ParseObject。

      希望你能解决你的问题..

      【讨论】:

      • 谢谢您的回复,但是我想上传一张图片,我应该将该图片视为文件吗?如何处理?
      • 是的,将图像视为文件。但是 parse.com 上的 Parse 指南说 为具有文件扩展名的文件命名很重要。这让 Parse 找出文件类型并相应地处理它。因此,如果您要存储 PNG 图像,请确保您的文件名以 .png 结尾。
      • 这甚至没有回答问题。
      【解决方案3】:
      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();
              }
      
           }
      

      【讨论】:

      • 嘿它对我没有用..,我想将图像保存为文件,我可以用 url 做什么..我将从相机捕获图像并在注册过程中分配给 imageview ,对于每个用户来说,图片都是不同的。,那么我怎样才能为不同的用户上传图片呢?
      • 嘿,谢谢..会试试这个,你能告诉我图片保存在哪里吗,因为我们没有为它创建任何列
      • 是的。没有文件列,也不应该存在于数据浏览器中,但仍然可以使用数据浏览器中的关系表下载文件。(上面代码中的 Table/Class UserDisplayImage)。除此之外,该文件也可以直接从它的 URL 访问。
      • 我可以为同一个类保存图像吗,可以说当我注册时它是在类(用户)上创建并保存字段值,就像我保存图像时一样创建一个像 UserDisplayImage 这样的类,而不是创建另一个类,我可以使用解析对象使用同一个类吗??
      • 是的,您可以在创建该用户时甚至在创建用户之后保存在同一个用户类中:user = ParseUser.getCurrentUser(); user.put("displayImage", file); user.save(); //handle exception here
      【解决方案4】:

      这样使用

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

      希望对你有帮助..

      【讨论】:

        【解决方案5】:

        Imageupload 和 Retriving 使用 Glide 解析的简单代码。

        图片上传

        destination_profile是你要上传图片路径的File对象。

            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");
                                        }
                                    });
                                }
                            });
        
        
                        }
                    });
                }
        

        图像检索

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

        【讨论】:

          【解决方案6】:

          假设你有你的位图文件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.
                  }
              });
          

          将位图转换为byte[],然后上传解析文件,然后再将其与解析对象相关联,这一点很重要。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-04-21
            • 2018-08-04
            • 2017-07-03
            • 2016-08-20
            • 1970-01-01
            • 2018-06-28
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多